You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目初始化加载时调用REST API并缓存数据的实现方法

Angular 全局复用API数据:初始化加载+本地存储方案

核心思路

通过Angular的APP_INITIALIZER钩子在应用启动时加载数据,同时将数据存入sessionStorage做缓存,后续页面直接复用缓存数据,避免重复请求API。

步骤实现

1. 封装全局数据服务

创建一个单例服务,统一处理数据请求、缓存读取和存储逻辑:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ColorMapService {
  private colormap = new Map<string, string>();
  // 替换成你的实际接口地址
  private FORWARD_URL = 'your-api-url';
  private specific_url = 'your-specific-url';

  constructor(private service: 你的Header服务类) {}

  // 从sessionStorage读取缓存数据
  private getCachedMap(): Map<string, string> | null {
    const cachedData = sessionStorage.getItem('colorMap');
    if (cachedData) {
      const parsedData = JSON.parse(cachedData);
      return new Map(Object.entries(parsedData));
    }
    return null;
  }

  // 将数据存入sessionStorage
  private saveToCache(map: Map<string, string>): void {
    const serializedData = JSON.stringify(Object.fromEntries(map));
    sessionStorage.setItem('colorMap', serializedData);
  }

  // 请求API获取原始数据
  private async fetchColorMap(): Promise<Map<string, string>> {
    const header = this.service.getHeader();
    this.service.addForwardUrlInHeader(header, this.specific_url);
    
    const response = await fetch(this.FORWARD_URL, header);
    if (response.status === 200) {
      const dataList = await response.json();
      const colorMap = new Map<string, string>();
      dataList.forEach((item: [string, string]) => {
        colorMap.set(item[0], item[1]);
      });
      return colorMap;
    } else {
      console.log('Failed to fetch color map data');
      return new Map();
    }
  }

  // 初始化方法:优先读缓存,无缓存则请求API
  async initColorMap(): Promise<void> {
    const cachedMap = this.getCachedMap();
    if (cachedMap) {
      this.colormap = cachedMap;
    } else {
      this.colormap = await this.fetchColorMap();
      this.saveToCache(this.colormap);
    }
  }

  // 提供全局获取colormap的方法
  getColorMap(): Map<string, string> {
    return this.colormap;
  }
}

2. 配置应用初始化钩子

在app.module.ts中配置APP_INITIALIZER,让应用启动时自动执行数据初始化:

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { ColorMapService } from './color-map.service';

// 初始化函数,返回Promise确保应用等待数据加载完成
function initColorMapService(service: ColorMapService) {
  return () => service.initColorMap();
}

@NgModule({
  // ...其他模块、组件配置
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initColorMapService,
      deps: [ColorMapService],
      multi: true
    }
  ]
})
export class AppModule { }

3. 组件中复用数据

在任意组件中直接注入服务获取colormap,无需重复请求:

import { Component } from '@angular/core';
import { ColorMapService } from './color-map.service';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html'
})
export class ExampleComponent {
  colormap: Map<string, string>;

  constructor(private colorMapService: ColorMapService) {
    this.colormap = colorMapService.getColorMap();
  }
}

关键说明

  • APP_INITIALIZER:确保数据在应用启动前加载完成,避免组件渲染时数据为空。
  • sessionStorage缓存:会话期间有效,关闭浏览器后自动清除;若需长期保存,可替换为localStorage。
  • 单例服务:通过providedIn: 'root'实现全局单例,所有组件共享同一数据实例。

内容的提问来源于stack exchange,提问作者student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:33:19