Angular2 缓存 HTTP 响应的最简单方法

5
我有一个页面,向同一位置发出http请求,只是根据用户的需求使用不同的参数。因此,我的代码看起来像这样:
this.http.post( //I am open to POST methods or GET methods as I have security in the back to prevent malicious writes.
   'http://192.168.1.45:3000/mylocation',
   'p1=' + param1 + '&p2=' + param2, 
   {headers: headers}
)

例如,在 JQuery 中,您已经在框架中构建了一个缓存属性,它可以自动缓存并且非常容易实现。
$.ajax({
  cache: true,
  //other options...
});

Angular2有类似的功能吗?我希望在用户使用应用程序时缓存这些动态响应,因此,如果用户使用相同的参数请求相同的URL,则只需从缓存中获取它,如果尚未使用参数,则会进行网络调用。
我在Angular2文档中的请求选项中找不到任何内容:

https://angular.io/docs/js/latest/api/http/RequestOptions-class.html

1个回答

10

缓存数据,如果有缓存数据则返回,否则进行HTTP请求。如果您想要为不同的请求(参数)重复使用,则可以调整为将引用存储在数组中。

getData() {
    if(this.data) {
      // if `data` is available just return it as `Observable`
      return Observable.of(this.data); 
    else if(this.observable) {
      // if `this.observable` is set then the request is in progress
      // return the `Observable` for the ongoing request
      return this.observable;
    } else {
      // create the request, store the `Observable` for subsequent subscribers
      this.observable = this.http.get('/someUrl')
          .map(res => res.json())
          .do(val => {
            this.data = val;
            // when the cached data is available we don't need the `Observable` reference anymore
            this.observable = null;
          })
          // make it shared so more than one subscriber can get the result
          .share();
      return this.observable;
    }
}

谢谢回复。我对observable非常陌生,所以有点难以理解,我肯定是漏掉了什么。如果我需要存储更多数据,我是否需要将this.data和数组结合起来?如果是这样的话,如何遍历数组并查看参数是否与data相同,因为data只会存储响应(data),而不是参数?谢谢。 - user2924127
当再次使用相同的参数调用方法时,您需要使用参数将数据存储以获取参数的缓存。 - Günter Zöchbauer
谢谢。我会研究一下,看看能否实现它。 - user2924127
1
我找到了一个更加优雅的解决方案,并已成功实现,网址为:http://www.syntaxsuccess.com/viewarticle/caching-with-rxjs-observables-in-angular-2.0。 - JLavoie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接