What is the correct way to share the result of an Angular Http network call in RxJs 5?

前端 未结 21 1327
广开言路
广开言路 2020-11-21 06:11

By using Http, we call a method that does a network call and returns an http observable:

getCustomer() {
    return          


        
21条回答
  •  醉酒成梦
    2020-11-21 06:13

    I starred the question, but i'll try and have a go at this.

    //this will be the shared observable that 
    //anyone can subscribe to, get the value, 
    //but not cause an api request
    let customer$ = new Rx.ReplaySubject(1);
    
    getCustomer().subscribe(customer$);
    
    //here's the first subscriber
    customer$.subscribe(val => console.log('subscriber 1: ' + val));
    
    //here's the second subscriber
    setTimeout(() => {
      customer$.subscribe(val => console.log('subscriber 2: ' + val));  
    }, 1000);
    
    function getCustomer() {
      return new Rx.Observable(observer => {
        console.log('api request');
        setTimeout(() => {
          console.log('api response');
          observer.next('customer object');
          observer.complete();
        }, 500);
      });
    }
    

    Here's the proof :)

    There is but one takeaway: getCustomer().subscribe(customer$)

    We are not subscribing to the api response of getCustomer(), we are subscribing to a ReplaySubject which is observable which is also able to subscribe to a different Observable and (and this is important) hold it's last emitted value and republish it to any of it's(ReplaySubject's) subscribers.

提交回复
热议问题