Angular/RxJS 6: How to prevent duplicate HTTP requests

angularangular6rxjsrxjs6

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 response and returns an Observable. Is it possible to share the first response with all subscribers to prevent duplicate HTTP requests?

Below is a simplified version of the scenario described above:

class SharedService {
  constructor(private http: HttpClient) {}

  getSomeData(): Observable<any> {
    return this.http.get<any>('some/endpoint');
  }
}

class Component1 {
  constructor(private sharedService: SharedService) {
    this.sharedService.getSomeData().subscribe(
      () => console.log('do something...')
    );
  }
}

class Component2 {
  constructor(private sharedService: SharedService) {
    this.sharedService.getSomeData().subscribe(
      () => console.log('do something different...')
    );
  }
}

Best Answer

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<any>;

  constructor(private http: HttpClient) {}

  getSomeData(): Observable<any> {
    if (this.someDataObservable) {
      return this.someDataObservable;
    } else {
      this.someDataObservable = this.http.get<any>('some/endpoint').pipe(share());
      return this.someDataObservable;
    }
  }
}

I am still open to more efficient suggestions!

For the curious: share()

Related Topic