Angular2缓存HTTP响应的最简单方法 [英] Angular2 easiest way to cache HTTP responses

查看:372
本文介绍了Angular2缓存HTTP响应的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面可以将http请求发送到同一个位置,只是根据用户的需要使用不同的参数。所以我的代码看起来像这样:

I have a page which makes http requests to the same location, just with different parameters depending on what the user wants. So my code looks something like this:

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中你已经构建了框架是一个缓存属性,它自动缓存并且非常容易实现:

In JQuery for example you have build into the framework a cache attribute which caches automatically and is very easy to implement:

$.ajax({
  cache: true,
  //other options...
});

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

Does Angular2 have something similar to this? I would like to cache these dynamic responses as long as the user is in the application. So if a user requests the same url with the same parameters then it would just grab it from the cache, and if the params were never yet used then it would make the network call.

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

I could not find anything in the Angular2 docs in the request options:

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

推荐答案

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

Cache the data, and if cached data is available return this, otherwise make the HTTP request. If you want to reuse for different requests (parameters) you can adjust to store the references in an array instead.

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;
    }
}

这篇关于Angular2缓存HTTP响应的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆