Home > other >  Prevent multiple identical http calls from Angular service
Prevent multiple identical http calls from Angular service

Time:05-10

I've a service to get the data from an API in my angular app. The service is used in different components - and the same http request is send multiple times. To prevent those multiple calls of the same data, I used the shareReplay() operator.

@Injectable({
    providedIn: "root",
})

export class CurrentValuesService {
   
    constructor(private http: HttpClient, private adapter: SingleMeasurePointAdapter) { }

    getLastEntry(): Observable<SingleMeasurePoint> {        

       ...
  
       let lastEntry = this.http.get(url)
          .pipe(            
             map((receivedData: any) => {
                console.log(receivedData);
                const data = ...              
                return data;
             }),
             shareReplay()            
          );
       return lastEntry;
    }
}

Calling the getLastEntry() function in the components:

ngOnInit(): void {
   this.currentValuesService.getLastEntry().subscribe((data: SingleMeasurePoint) => {
      ...       
   });
}

But nothing changes - the same request is send for every subscribing component again - and not only once.

Am I totally wrong? Or are there other ways to prevent multiple calls?

CodePudding user response:

You could use SharedDataService to save Your request response and use it in other pages:

SharedDataService has as variables and methods:

_lastEntry // declare your var

get lastEntry(){
return this._lastEntry;

}
set lastEntry(value){
this._lastEntry = value;
}

Then on your component check if it has a value:

constructor(public sharedDataService : SharedDataService){}

ngOnInit(): void {

let lastEntry = this.sharedDataService.lastEntry
if(!lastEntry){
 this.currentValuesService.getLastEntry().subscribe((data: SingleMeasurePoint) => {
this.lastEntry = lastEntry

      ...       
   });
}

else{
this.lastEntry = lastEntry

}


  
}

CodePudding user response:

Maybe you have a look at the proposal here: Caching

Look at the second code snippet: A member variables is used for storing the returned observable from http client.

  • Related