Angular - 缓存http响应的最佳方式
答
在这里你会找到多个答案:Angular 2 cache observable http result data
我会建议建立简单的类可缓存<>,有助于从HTTP服务器或其他任何其他来源获取的数据管理缓存:
declare type GetDataHandler<T> =() => Observable<T>;
export class Cacheable<T> {
protected data: T;
protected subjectData: Subject<T>;
protected observableData: Observable<T>;
public getHandler: GetDataHandler<T>;
constructor() {
this.subjectData = new ReplaySubject(1);
this.observableData = this.subjectData.asObservable();
}
public getData(): Observable<T> {
if (!this.getHandler) {
throw new Error("getHandler is not defined");
}
if (!this.data) {
this.getHandler().map((r: T) => {
this.data = r;
return r;
}).subscribe(
result => this.subjectData.next(result),
err => this.subjectData.error(err)
);
}
return this.observableData;
}
public resetCache(): void {
this.data = null;
}
public refresh(): void {
this.resetCache();
this.getData();
}
}
使用方法
声明Cacheable <> object(推测可以作为服务的一部分):
list: Cacheable<string> = new Cacheable<string>();
和处理程序:从组件
this.list.getHandler =() => {
// get data from server
return this.http.get(url)
.map((r: Response) => r.json() as string[]);
}
电话:
//gets data from server
List.getData().subscribe(…)
更多细节和代码示例在这里:http://devinstance.net/articles/20171021/rxjs-cacheable
有一个关于HttpClient的文档中的缓存部分。到目前为止你尝试过什么,哪些不适合你? https://angular.io/guide/http#caching – Duncan
感谢您的回应! –