【发布时间】:2017-11-21 00:01:08
【问题描述】:
我需要在我的服务中缓存服务器响应。我检查了这个问题caching results with angular2 http service,在这里我找到了两种方法 1) Observable.share() - 但正如答案中所说“他 share() 运算符仅在第一个请求时工作,当所有订阅都服务并且您创建另一个,然后它将不起作用,它将发出另一个请求” 2)使用 ReplaySubject 在使用解析器之前效果很好(它正在创建新请求)。这是我的 plunker https://plnkr.co/edit/TiODzGyQtXepojf4oPgw 你可以检查网络选项卡,当你从组件 A 导航到组件 B 时,两种方式都会创建新请求。知道如何解决这个问题吗?
我的服务
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import * as Rx from 'rxjs';
import { Http } from '@angular/http';
import { ReplaySubject } from 'rxjs/ReplaySubject';
@Injectable()
export class ContactsService {
goals: ReplaySubject<Array<any>> = new ReplaySubject(1);
constructor(private http: Http) {}
get() {
if (!this.goals.observers.length) {
return this.http
.get('https://jsonplaceholder.typicode.com/posts/1');
}
return this.goals;
}
get2() {
return this.http
.get('https://jsonplaceholder.typicode.com/posts/1').share();
}
}
更新
对于科目,您可以使用以下方法(由 ehrencrona 建议)
cache: ReplaySubject<Array<any>>
get() {
if (!this.cache) {
this.cache = new ReplaySubject(1)
this.http.get(url).subscribe(this.cache)
}
return this.cache
}
对于 observable 你可以使用我发现的这个方法
observable: Observable<any>;
get() {
if (!this.observable) {
this.observable = this.http.get(url).publishReplay(1).refCount();
}
return this.observable;
}
请注意 .publishReplay(1).refCount() 与 .share() 不同 - 使用 .share() 它不会创建新请求
【问题讨论】:
-
请注意,如果你在 http.get 之前放置一个 console.log,它永远不会被调用。所以
!this.dataObs$.observers.length似乎不是测试 ReplaySubject 是否有值的最佳方法。它计算订阅者的数量。
标签: angular rxjs observable