How to call single ajax request by multiple components parallely in angular2 cli project

前端 未结 1 1302
醉酒成梦
醉酒成梦 2021-01-22 10:59

The scenario is , there is a single service(json-data-service.ts) having a method getWebservicedata() which returns http.post(url) ie it makes an ajax call when method is called

相关标签:
1条回答
  • 2021-01-22 11:36

    You want something using the rxjs .share() method (https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/share.md). Basically it allows multiple subscribers to share the same observable sequence.

    export class Service {
      observableShare: Observable<string>; // store the shared observable
      
      constructor(private http: Http){}
      
      getData(){
        if(this.observableShare){ // if api is still processing, return shared observable
            return this.observableShare;
        }else{ // else api has not started, start api and return shared observable
          this.observableShare = this.http.post('url')
            .map(res => res.json())
            .share(); // share observable sequence among multiple subscribers
          
          return this.observableShare;
        }
        
      }
    }

    Here is a working plunkr (https://plnkr.co/edit/MU4aoFI34ZGjjtQ5wS9j?p=preview) you can see in the console, 3 separate subscribes are sharing the same observable sequence (http request).

    Here is another example goes one step further and stores the result in the service (https://plnkr.co/edit/M9ZIViYhSbKzPlzKXC7H?p=preview). This acts as a cache, so if a component that is loaded later needs the data, an additional api call is not needed. But you do not need that functionality for this piece.

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