use*_*127 5 javascript caching http typescript angular
我有一个页面,它将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}
)
Run Code Online (Sandbox Code Playgroud)
例如,在JQuery中,您已经在框架中构建了一个缓存属性,该属性可以自动缓存并且非常容易实现:
$.ajax({
cache: true,
//other options...
});
Run Code Online (Sandbox Code Playgroud)
Angular2有类似的东西吗?只要用户在应用程序中,我想缓存这些动态响应.因此,如果用户使用相同的参数请求相同的url,那么它只是从缓存中获取它,如果从未使用过params,那么它将进行网络调用.
我在请求选项中的Angular2文档中找不到任何内容:
https://angular.io/docs/js/latest/api/http/RequestOptions-class.html
Gün*_*uer 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9350 次 |
| 最近记录: |