Angular/RxJS 6: How to prevent duplicate HTTP requests?

前端 未结 6 1516
自闭症患者
自闭症患者 2020-12-29 21:35

Currently have a scenario where a method within a shared service is used by multiple components. This method makes an HTTP call to an endpoint that will always have the same

6条回答
  •  爱一瞬间的悲伤
    2020-12-29 21:51

    After trying a few different methods, came across this one that resolves my issue and only makes one HTTP request no matter how many subscribers:

    class SharedService {
      someDataObservable: Observable;
    
      constructor(private http: HttpClient) {}
    
      getSomeData(): Observable {
        if (this.someDataObservable) {
          return this.someDataObservable;
        } else {
          this.someDataObservable = this.http.get('some/endpoint').pipe(share());
          return this.someDataObservable;
        }
      }
    }
    

    I am still open to more efficient suggestions!

    For the curious: share()

提交回复
热议问题