簡體   English   中英

如何在angular項目上調用rest API加載和保存數據?

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

我試圖通過減少訪問 API 端點以獲取數據的次數來提高我的代碼的性能。 我是 angular 的新手,有人可以幫助我了解如何從 API 端點獲取數據並將其存儲到會話(或其他東西)中,以便它可以在應用程序的其他地方使用嗎? 目前,我在每次頁面加載時都會獲取這些數據。 這是代碼:


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])
    }
  }

我想在初始項目加載中填充顏色圖 object 中的數據。

也許創建一個存儲您的端點響應的服務。 然后,每次你想得到它時,你檢查它是否存在,否則,調用端點。

服務:

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;
        }
    }
}

組件:

@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();
        
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM