【问题标题】:Angular - best way to cache http responseAngular - 缓存 http 响应的最佳方式
【发布时间】:2018-03-16 00:40:20
【问题描述】:

我有很多服务请求休息服务,我想缓存从服务器接收的数据以供进一步使用。 谁能告诉现金回应的最佳方式是什么?

【问题讨论】:

  • HttpClient 文档中有一个关于缓存的部分。到目前为止,您尝试了什么,什么对您不起作用? angular.io/guide/http#caching
  • 感谢您的回复!

标签: angular http typescript caching


【解决方案1】:

您会在这里找到多个答案:Angular 2 cache observable http result data

我会建议构建简单的类 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();
    }

}

用法

声明可缓存对象(大概是服务的一部分):

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

【讨论】:

  • 感谢您在回答中发布链接。
【解决方案2】:

您还可以使用 Angular 4+ 版本的 http 拦截器。一个非常详细和直接的实现,带有解释-https://www.concretepage.com/angular/angular-caching-http-interceptor

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 2011-05-29
    • 2021-11-12
    • 2023-02-12
    • 2010-09-05
    • 1970-01-01
    相关资源
    最近更新 更多