Home > front end >  How to share api response between multiple Angular Components?
How to share api response between multiple Angular Components?

Time:04-18

I am trying to wrap my head around & use BehaviourSubject in Angular (so far without much luck). My goal is to share the api request response across my components.

Here's a stackblitz setup of what my project looks like:

https://stackblitz.com/edit/angular-ivy-3cql7e?file=src/app/apicaller.service.ts

In the console/network tab, there's currently three requests being made to the api.

How can I work with these so that only one api request is used for component1 and component2


For a visual overview of this problem, here's a quick diagram:

                 -------------------                               
                |                   |                              
                | apicaller.service | (api being called here)      
                |                   |                              
                 -------------------                               
                                                                   
           ----------        -------------                         
          |component1|      |component2   |                        
           ----------        -------------                         
                  Use only 1 api call                              
                  to get data across                               
                  x amount of components                           
                                               

CodePudding user response:

You have wrong code in the method getData() in your service - it returns every time a new http request instead of sharing one. Just add another observable property in the service to solve this problem. Add inside pipe shareReplay() to make this observable hot after first subscription and then it will share the data. Like this:

private readonly request = this._http
  .get('https://swapi.dev/api/people/')
  .pipe(
    map((result) => result['results']), 
    shareReplay(),
  );

getData() {
  console.log(Math.random() * 100   ' getData()');
  // count api request
  // return as array of objects
  return this.request;
}
  • Related