Angular中API响应缓慢问题。
创始人
2024-10-31 00:30:24
0
  1. 使用Observable的pipe和map操作符来缓存API响应。
import { of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private api = 'https://api.example.com'; // API URL

  constructor(private http: HttpClient) { }

  public getData(endpoint: string, cacheTime?: number): Observable {
    let url = `${this.api}/${endpoint}`;

    // Check if we should use cached data
    if (localStorage.getItem(url) && cacheTime && cacheTime > 0) {
      const inCacheSince = parseInt(localStorage.getItem(url + '_timestamp'), 10);
      const ageInMinutes = Math.floor((Date.now() - inCacheSince) / 1000 / 60);

      if (ageInMinutes < cacheTime) {
        return of(JSON.parse(localStorage.getItem(url)));
      }
    }

    // Retrieve data from API
    return this.http.get(url).pipe(
      map(data => {
        // Store response in cache
        localStorage.setItem(url, JSON.stringify(data));
        localStorage.setItem(url + '_timestamp', Date.now().toString());

        return data;
      }),
      catchError(error => {
        console.log(error);
        return throwError('Something went wrong!'); // TODO: Customize error message
      })
    );
  }
}
  1. 添加缓存拦截器来缓存API响应:
import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
  private cache = new Map();

  intercept(request: HttpRequest, next: HttpHandler): Observable> {
    if (request.method !== 'GET') {
      return next.handle(request);
    }

    const cachedResponse = this.cache.get(request.urlWithParams);
    if (cachedResponse) {
      return of(cachedResponse);
    }

    return next.handle(request).pipe(
      tap(event

相关内容

热门资讯

红龙扑克辅助工具!红龙扑克好友... 红龙扑克辅助工具!红龙扑克好友桌,(红龙扑克)果然有挂(详细辅助器教程);科技安装教程;136704...
微扑克辅助挂!wpk微扑克外挂... 微扑克辅助挂!wpk微扑克外挂事件,(微扑克规律)原来存在有挂(详细ai辅助器苹果版教程);超受欢迎...
wepower辅助器!wepo... 1、wepower辅助器!wepower透视辅助(wepoke app)好像真的是有挂(详细有挂教程...
红龙扑克辅助挂!红龙扑克辅助工... 红龙扑克辅助挂!红龙扑克辅助工具,(红龙扑克)总是真的有挂(详细辅助器教程),亲,有的,ai轻松简单...
WePoKe透明挂!wepok... WePoKe透明挂!wepoke用模拟器有什么用(Wepoke透明)真是有挂(详细真的有挂教程)关于...
aapoker透视辅助!aa扑... aapoker透视辅助新手教程相关信息汇总(需添加指定薇757446909获取下载链接);aapok...
德扑开发!德扑之星真的有辅吗,... 德扑开发!德扑之星真的有辅吗,德扑之星专业确实真的有挂(详细数据教程);亲真的是有正版授权,小编(透...
wepoke真的有挂!wepo... wepoke真的有挂新手教程相关信息汇总(需添加指定薇757446909获取下载链接);wepoke...
德扑之星发牌!德扑之星的机制,... 德扑之星发牌!德扑之星的机制,德扑之星ai软件好像真的有挂(详细线上教程)1、完成的残局,帮助玩家取...
红龙扑克辅助器!红龙扑克有挂么... 红龙扑克辅助器!红龙扑克有挂么,(红龙扑克)竟然有挂(详细辅助教程)平台为新手玩家设计了多种软件透明...