Converting Angular2 Http response to ConnectableObservable

前端 未结 1 808
日久生厌
日久生厌 2021-01-14 23:06

I must admit that I am doing my first steps with Angular2, and I am running into an issue here, which I have some problems understanding. I am using angular2@2.0.0-beta.0, w

1条回答
  •  时光说笑
    2021-01-14 23:41

    In fact, I think that using a ConnectableObservable isn't necessary. Here is the test I made and both subscribers are called when the response is received:

    var observable =
      this.http.get('https://angular2.apispark.net/v1/companies/')
               .map(res => res.json());
    
    observable.subscribe(
      data => console.log('subscribe #1'));
    observable.subscribe(
      data => console.log('subscribe #2'));
    

    Edit

    I think that the share operator can fit your needs:

    var observable =
      this.http.get('https://angular2.apispark.net/v1/companies/')
               .map(res => res.json()).share();
    
    observable.subscribe(
      data => console.log('subscribe #1'));
    observable.subscribe(
      data => console.log('subscribe #2'));
    

    It allows to create a connectable observable (the share method returns an hot observable). In this case, only one HTTP request is executed...

    This question could be helpful for you: Hot and shared Observable from an EventEmitter.

    Edit1

    After some discussions in comments, it appears that the question was about why the follwing error occurs: TypeError: obs.share is not a function and why are almost all of the documented functions not available in the observable returned by the post function.

    So the solution was to explicitly import RxJS operators to make them available at runtime.

    There are two solutions. Importing per operator:

    import 'rxjs/add/operator/map'
    

    Or more generally this if you want to have all available operator methods for observables:

    import 'rxjs/Rx';
    

    Hope it helps you, Thierry

    0 讨论(0)
提交回复
热议问题