1

How to avoid multiple http requests when same component is used twice in template

https://stackblitz.com/edit/angular-8sgrgz

hello component is used twice in the template and its making calling service method for http data

  return this.http
    .get('https://api.openweathermap.org/data/2.5/weather? 
      q=London&appid=517c7bbf790248290ad52d57725c4d5f')
    .map((res) => {return res.json()})
                  .catch((error:any) => 
                       Observable.throw(error.json().error || 'Server 
     error')).share();} 

the http request should happen only once 
but its happening more than once
3
  • 5
    Don't get the data directly from http, add a singleton service and inject it in the component and use a BehaviorSubject to store the fetched data. Commented May 2, 2019 at 6:09
  • if you check in the stackblitz link mentioned I have already done it in a service Commented May 2, 2019 at 7:04
  • 1
    Yeah, but you have to cache your requests. I'll add the answer in a minute. Commented May 2, 2019 at 7:34

1 Answer 1

1

Add the Behaviour subject to hold your data once you fetch it:

private data$: BehaviorSubject<any> = new BehaviorSubject(null);

Add a function to get data:

  getData() {
    return this.data$.pipe(
      switchMap(data => {
        if (data) {
          return of(data); // If data was saved, just return it (you're actually returning an observable of data, because switchMap needs observables to switch for every other observable emission)
        } else {
          return this.http.get("") // If it wasn't, make a new http request
            .pipe(tap(newData => this.data$.next(newData))); // And save the data on the subject
        }
      })
    );
  }

Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.