Home > Back-end >  How to caches API response in a service in Angular
How to caches API response in a service in Angular

Time:04-21

I have an angular component which gets data from a service of common phrases. I've included the relevant code here, which is the component getting the data from an API.

My problem is that this component is used in many areas in a nested form, and so the API call to getPhrases() gets called multiple times.

I've tried to cache this in my service, but that hasn't worked - maybe because the service is being created each time as well?

What's the best way to only call the API once per session?

export class MentionDirective implements OnInit, OnChanges {
  phrases: any[];

  constructor(
    public mentionService: MentionService
  ) { }

  ngOnInit() {
    this.mentionService.getPhrases()
      .subscribe(
        result => {
          this.phrases = result;              
        },
        () => { });

  }

}

Here's the service:

export class MentionService {

    constructor(private http: HttpClient) { }

    private phrases$: Observable<string[]>;

    public getPhrases(): Observable<string[]> {
        if (!this.phrases$) {
            this.phrases$ = this.http.get<string[]>(this.baseUrl   '/getAutocompletePhrasesList');
        }
        return this.phrases$;
    }
}

This is how I call my directive:

<input matInput mention formControlName="message" required>

CodePudding user response:

If you try simple snippet:

const obs = this.http.get....;
obs.subscribe(() => console.log('test'));
obs.subscribe(() => console.log('test'));

You will see that http request is sent each time you subscribe, too avoid that you just need pipe(share()).

CodePudding user response:

I normally use localStorage to cache loaded datas from API. Then I need to check the localStogage first. If localStorage is empty, I just call the API again.

https://www.w3schools.com/jsref/prop_win_localstorage.asp

  ngOnInit() {
    if(localStorage.getItem('phrases') === null){
    this.mentionService.getPhrases()
      .subscribe(
        result => {
          this.phrases = result;
          localStorage.setItem('phrases', result);
        },
        () => { });
    }else{
      this.phrases = localStorage.getItem('phrases');
    }

  }
  • Related