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

相关内容

热门资讯

透视专业!wpk有那种辅助吗(... 透视专业!wpk有那种辅助吗(透视)约局吧如何查看是否有挂,教程技法(有挂技术)-哔哩哔哩约局吧如何...
透视透视!wepokerplu... 透视透视!wepokerplus脚本(透视)wepoker透视脚本苹果版,教程操作(了解有挂)-哔哩...
透视透视!hhpoker可以控... 透视透视!hhpoker可以控制牌吗(透视)hardrock透视,教程要领(有挂透视)-哔哩哔哩1、...
透视必备!wepoker轻量版... 透视必备!wepoker轻量版透视(透视)wepoker黑侠辅助器正版下载,教程指南(有挂细节)-哔...
透视揭幕!pokemmo辅助器... 透视揭幕!pokemmo辅助器(透视)wepoker透视挂底牌,教程诀窍(有挂总结)-哔哩哔哩1、进...
透视专业!悦扑克脚本(透视)德... 透视专业!悦扑克脚本(透视)德州局透视脚本,教程教程书(有挂方式)-哔哩哔哩1、玩家可以在德州局透视...
透视总结!wepoker辅助器... 透视总结!wepoker辅助器软件下载(透视)hhpoker有后台操控吗,教程经验(有挂存在)-哔哩...
透视曝光!wepoker免费辅... 透视曝光!wepoker免费辅助器(透视)wpk透视怎么安装,教程窍要(有挂攻略)-哔哩哔哩1、进入...
透视总结!哈糖大菠萝有挂吗(透... 透视总结!哈糖大菠萝有挂吗(透视)wepoker有脚本吗,教程大纲(有挂方针)-哔哩哔哩1、任何哈糖...
透视总结!hhpoker软件可... 您好,hhpoker软件可以玩吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【48527505...