无法订阅可观察的

时间:2019-03-31 18:14:56

标签: angular rxjs

我有一个deviceManager服务,该服务加载要从后端跟踪的设备列表。有时这可能需要一段时间,所以我希望初始的app.component加载数据。我有通过httpClient调用的服务,并且我希望app.component可以订阅该服务。但是编译器告诉我,当我显式返回observable类型时,我不能订阅void类型。这是服务:

export class DeviceManagerService {
  public deviceDBSubject = new BehaviorSubject<any[]>([]);
  private loadingSubject = new BehaviorSubject<boolean>(false);
  public loading$ = this.loadingSubject.asObservable();

  private deviceDB: Device[];

  constructor(private apiService: ApiService) { }

  getAllDevices() {
    this.loadingSubject.next(true);
    this.apiService.getAllDevices().subscribe( devices => {
      this.deviceDB = devices;
      this.deviceDBSubject.next(this.deviceDB);

      console.log('devices are: ', this.deviceDB);
      this.loadingSubject.next(false);
      return this.deviceDBSubject.asObservable();
    });
  }
}

这就是我要在我的app.component中调用它的地方

    const deviceManagerObservable = this.deviceManagerService.getAllDevices();
     deviceManagerObservable.subscribe((devices) => {
       this.deviceDB = devices;
       console.log('devices are: ', this.deviceDB);
       this.loadingSubject.next(false);
     });

我在做什么错了?

谢谢.....

1 个答案:

答案 0 :(得分:1)

您没有在getAllDevices()中返回任何内容,因此您无法订阅

最重要的是,您需要对其进行观测,因此您不能在getAllDevices()中使用.subscribe,而是需要使用修饰符将Observable传递给管道

return this.apiService.getAllDevices().pipe(
   switchMap( devices => {
      this.deviceDB = devices;
      this.deviceDBSubject.next(this.deviceDB);

      console.log('devices are: ', this.deviceDB);
      this.loadingSubject.next(false);
      return this.deviceDBSubject.asObservable();
    }));
  }

大概是这样

相关问题