如何使用 rxjs observables 为缓存的 Angular2 http 响应添加到期时间 [英] How to add an expiry time for cached Angular2 http response using rxjs observables

查看:55
本文介绍了如何使用 rxjs observables 为缓存的 Angular2 http 响应添加到期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 rxjs publishReplay(1)refCount 来缓存 http 响应.为缓存设置到期时间的最佳方法是什么.我正在使用每 1 小时到期的 http 调用获取令牌.

I am using rxjs publishReplay(1) and refCount to cache http response. What's the best way to put an expiry time for the caching. I am getting a token using http call which expires every 1 hour.

@Injectable()
export class SearchService{
public url: string;
private token:Observable<any> = null;

constructor(private _http:Http){

}

getSecurityToken(url:string): any {

    headers.append("securitycode","*******");

    if(!this.token){
        this.token = this._http.post(url,{headers:headers})
            .map(this.extractData)
            .publishReplay(1)
            .refCount()
            .catch(this.handleError);
    }
    return this.token;
}     


private extractData(res: Response) {
    console.log(res.status);
    if(res.status == 204) { 
        return [];
    }
    else{
        let body = res.json();
        return body;
    }
}

private handleError (error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
   console.error(errMsg); // log to console instead
   return Observable.throw(errMsg);
}

推荐答案

publishReplay 在内部使用 ReplaySubject 作为第二个参数定义多长时间的时间窗口每个缓存项是否有效.

The publishReplay internally uses the ReplaySubject that takes as the second argument the time window which defines how long is each cached item valid.

因此,在您的情况下,它可能是例如:

So in your case it could be for example:

...
.publishReplay(1, 60 * 1000)

参见:http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-publishReplay

这篇关于如何使用 rxjs observables 为缓存的 Angular2 http 响应添加到期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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