简体   繁体   中英

How to call rest API on angular project load and preserve the data?

I am trying to improve the performance of my code by reducing the number of times it will hit the API endpoint to get data. I am new to angular, can someone help me with how I can get the data from an API endpoint and store it into a session(or something else) so that it can be used elsewhere in the application? Currently, I am getting this data on every page load. This is the code for that:


colormap = new Map<string, string>(); 

async abc()
  {
    const header = this.service.getHeader();
    this.service.addForwardUrlInHeader(header, this.specific_url );
    return fetch(
      this.FORWARD_URL,
      header
    ).then(response =>
    {
      if (response.status === 200)
      {
        return response.json();
      } else
      {
        console.log('Unable To Get');
      }
    });
  }


  async loadmap(){
    let lst: Array<object> = [];
    lst=await this.abc();
    for(let i=0;i<lst.length;i++){
      this.colormap.set(lst[i][0],lst[i][1])
    }
  }

I want to populate data in colormap object in initial project load.

Maybe creating a service that stores your endpoint response. Then, each time you want to get it, you check if it exists, else, call the endpoint.

The service:

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";

@Injectable({ providedIn: 'root' })
export class StoredDataService {
    private myStoredData = new BehaviorSubject<any>(null);

    constructor(private httpClient: HttpClient) {

    }

    public async getMyData(): Promise<any> {
        if (this.myStoredData.value) {
            return Promise.resolve(this.myStoredData.value);
        } else {
            const myFreshlyLoadedData = await this.httpClient.get('...').toPromise();
            this.myStoredData.next(myFreshlyLoadedData);
            return this.myStoredData.value;
        }
    }
}

The component:

@Component({
    template: '...'
})
export class MyComponent implements OnInit {
    constructor(private storedDataService: StoredDataService) {

    }

    ngOnInit(): void {
        this.load();
    }

    private async load(): Promise<void>{
        // Will call the api 
        await this.storedDataService.getMyData();
        
        // Will just return the stored data without calling the api
        await this.storedDataService.getMyData();
        await this.storedDataService.getMyData();
        await this.storedDataService.getMyData();
        await this.storedDataService.getMyData();
        await this.storedDataService.getMyData();
        await this.storedDataService.getMyData();
        
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM