cpeddie
cpeddie

Reputation: 799

can't subscribe to observable

I have a deviceManager service that loads a list of devices to track from a backend. This can sometimes take awhile, so I want the initial app.component to load the data. I have my service calling via httpClient and I want app.component to subscribe to the service. But the compiler is telling me I can't subscribe to type void when I am explicitly returning type observable. Here is the service:

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();
    });
  }
}

and here is where I'm trying to call it in my app.component

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

What am I doing wrong?

Thanks.....

Upvotes: 0

Views: 1210

Answers (1)

jonathan Heindl
jonathan Heindl

Reputation: 861

you are not returning anything in getAllDevices() so you cant subscribe to it

on top of that you need to keep it a observale so you cant use .subscribe in the getAllDevices() instead you need to pipe the observable with modifiers

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();
    }));
  }

probably like this

Upvotes: 1

Related Questions