首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular2缓存HTTP响应的最简单方法

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

Stack Overflow用户
提问于 2016-03-30 03:55:30
回答 1查看 9.8K关注 0票数 5

我有一个页面,使http请求到相同的位置,只是不同的参数取决于用户想要什么。所以我的代码看起来像这样:

代码语言:javascript
复制
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中,你已经在框架中构建了一个缓存属性,它可以自动缓存,并且非常容易实现:

代码语言:javascript
复制
$.ajax({
  cache: true,
  //other options...
});

Angular2有类似的东西吗?只要用户在应用程序中,我就会缓存这些动态响应。因此,如果用户用相同的参数请求相同的url,那么它就会从缓存中获取它,如果参数从未使用过,那么它就会进行网络调用。

我在请求选项的Angular2文档中找不到任何内容:

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

EN

回答 1

Stack Overflow用户

发布于 2016-03-30 03:59:18

缓存数据,如果缓存的数据可用,则返回this,否则发出HTTP请求。如果您想重用不同的请求(参数),您可以调整以将引用存储在一个数组中。

代码语言:javascript
复制
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;
    }
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36293938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档