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

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

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()

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)