在Angular 4中,可以使用HTTP Interceptor来实现缓存数据的功能。下面是一个示例:
CacheInterceptor
的新文件,并添加以下代码:import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpResponse, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class CacheInterceptor implements HttpInterceptor {
private cache: Map> = new Map();
intercept(request: HttpRequest, next: HttpHandler): Observable> {
if (request.method !== 'GET') {
// 不缓存非GET请求
return next.handle(request);
}
const cachedResponse = this.cache.get(request.url);
if (cachedResponse) {
return of(cachedResponse.clone());
}
return next.handle(request).pipe(
tap(event => {
if (event instanceof HttpResponse) {
this.cache.set(request.url, event.clone());
}
})
);
}
}
app.module.ts
文件中,将CacheInterceptor
添加到HTTP_INTERCEPTORS
提供商中:import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { CacheInterceptor } from './cache.interceptor';
@NgModule({
imports: [BrowserModule, HttpClientModule],
declarations: [AppComponent],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: CacheInterceptor,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,当进行GET请求时,如果响应已经被缓存,则会直接返回缓存的响应。如果响应未被缓存,则会发送请求,并将响应缓存起来,以便下次使用。