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

前端 未结 6 1533
自闭症患者
自闭症患者 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:59

    Singleton service & component.ts works same as before

    1. Make sure your service is singleton
    2. Return a new Observable, instead of http.get Observable
    3. First time make the HTTP request, save response & update the new observable
    4. Next time onwards update the observable without HTTP request

    .

    class SharedService {
    
        private savedResponse; //to return second time onwards
    
        constructor(private http: HttpClient) {}
    
        getSomeData(): Observable {
    
          return new Observable((observer) => {
    
            if (this.savedResponse) {
    
              observer.next(this.savedResponse);
              observer.complete();
    
            } else { /* make http request & process */
              
              this.http.get('some/endpoint').subscribe(data => {
                this.savedResponse = data; 
                observer.next(this.savedResponse);
                observer.complete();
              }); /* make sure to handle http error */
    
            }
    
          });
        }
      }
    

    You can verify singleton by placing a random number variable in the service. console.log should print the same number from everywhere!

        /* singleton will have the same random number in all instances */
        private random = Math.floor((Math.random() * 1000) + 1);
    

    The advantage: This service even after this update returns observable in both cases (http or cache).

    Note: Make sure the provider for this service is not added individually in each component.

提交回复
热议问题