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

相关内容

热门资讯

黑科技代打(德州alphax)... 黑科技代打(德州alphax)微扑克ai一贯存在有挂!太嚣张了起初真的有挂(2026已更新)(哔哩哔...
黑科技辅助挂挂(德扑安装)德州... 黑科技辅助挂挂(德扑安装)德州app切实真的有挂!太无语了果然是真的有挂(2021已更新)(哔哩哔哩...
黑科技肯定(扑克时间后台数据)... 黑科技肯定(扑克时间后台数据)pokerrrr2从前存在有挂!太嚣张了从来是有挂(2022已更新)(...
黑科技总结(WPK计算器)po... WePoker透视辅助版本解析‌,黑科技总结(WPK计算器)pokenow原本真的有挂!太夸张了好像...
黑科技教程(WPK)德扑ai总... 黑科技教程(WPK)德扑ai总是是有挂!太嚣张了切实是真的有挂(2022已更新)(哔哩哔哩);人气非...
黑科技软件(德扑之星自定义)来... 黑科技软件(德扑之星自定义)来玩德州固有是有挂!太无语了总是存在有挂(2022已更新)(哔哩哔哩);...
黑科技ai代打(wepoke线... 黑科技ai代打(wepoke线上)微扑克游戏切实是真的有挂!太夸张了原先有挂(2026已更新)(哔哩...
黑科技安装(Wepoke智能)... 黑科技安装(Wepoke智能)wpK原先真的是有挂!太实锤了从来真的是有挂(2025已更新)(哔哩哔...
黑科技总结(pokermast... 黑科技总结(pokermaster)AAPOKeR一贯是有挂!太夸张了切实是真的有挂(2024已更新...
黑科技安卓版(Wepoke私人... 黑科技安卓版(Wepoke私人局)nzt德州原来真的是有挂!太夸张了往昔存在有挂(2021已更新)(...