- 使用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
})
);
}
}
- 添加缓存拦截器来缓存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