[英]Angular - best way to cache http response
I have a lot of services with requests to rest service and I want to cache data receive from server for further usage.我有很多服务请求休息服务,我想缓存从服务器接收的数据以供进一步使用。 Could anyone tell what is the best way to cash response?
谁能告诉现金回应的最佳方式是什么?
You will find multiple answers here: Angular 2 cache observable http result data你会在这里找到多个答案: Angular 2 cache observable http result data
I would recommend to build simple class Cacheable<> that helps managing cache of data retrieved from http server or other any other source:我建议构建简单的类 Cacheable<> 来帮助管理从 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();
}
}
Usage用法
Declare Cacheable<> object (presumably as part of the service):声明 Cacheable<> 对象(大概作为服务的一部分):
list: Cacheable<string> = new Cacheable<string>();
and handler:和处理程序:
this.list.getHandler = () => {
// get data from server
return this.http.get(url)
.map((r: Response) => r.json() as string[]);
}
Call from a component:从组件调用:
//gets data from server
List.getData().subscribe(…)
More details and code example are here: http://devinstance.net/articles/20171021/rxjs-cacheable更多细节和代码示例在这里: http ://devinstance.net/articles/20171021/rxjs-cacheable
You can also use http interceptors with angular 4+ versions.您还可以使用 Angular 4+ 版本的 http 拦截器。 A very detailed and straight-forward implementation with explanation- https://www.concretepage.com/angular/angular-caching-http-interceptor
一个非常详细和直接的实现与解释 - https://www.concretepage.com/angular/angular-caching-http-interceptor
For GET responses, you can try using this get shell component, which is super easy to use and set the cache configurations.对于 GET 响应,您可以尝试使用这个 get shell 组件,它非常易于使用和设置缓存配置。 ngx-http-get-shell
ngx-http-get-shell
<ngx-http-get-shell [url]="url" [maxStale]="1000" [templateRef]="tmpl">
<ng-template #tmpl let-data>
{{ data | json }}
</ng-template>
</ngx-http-get-shell>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.