observableangular7

Angular observable / subscribe not working


I'm trying to get a value from an observable with angular 7. I have some functions inside a service that look like this

getSomething(): Observable<MyObject[]> {
  let result = new Subject<MyObject[]>();
  this.callApi('hello-world').subscribe(data => {
      console.log('hello-world data: ', data);
      result.next(this._mapToMyObjectArray(data));
  });
  return result.asObservable();
}

_mapToMyObjectArray(data: any): MyObject[] {
    ...
}

I'm able to log the hello-world data with no problem (the api is called and responds as I expect).

However, when I try to subscribe to this from another component, such as

doStuff(): void {
    console.log('do stuff with something');
    this.myService.getSomething().subscribe(
        (result) => console.log('result', result),
        (error) => console.log('error', error),
        () => console.log('done')
     );
}

When I invoke doStuff() I see the first log (do stuff with something) but not the other logs (success / error / done).

Can anyone provide some insight? Thanks for your help, I'm sure it's something trivial.


Solution

  • Hopefully this can help someone. I had a fundamental misunderstanding of the difference between subjects and observers. See here.

    I solved it by creating an observer instead of a subject within the getSomething function.

    getSomething(): Observable<MyObject[]> {
      var result: Observable<MyObject[]>;
      this.callApi('hello-world').subscribe(data => {
          console.log('hello-world data: ', data);
          result = of(this._mapToMyObjectArray(data));
      });
      return result;
    }
    

    where of is imported from rxjs.