我创建了一个发出简单GET请求的服务:
private accountObservable = null;
constructor(private _http: Http) {
}
getAccount () {
// If we have account cached, use it instead
if (this.accountObservable === null) {
this.accountObservable = this._http.get('http://localhost/api/account')
.map(res => <Account> res.json().data)
.catch(this.handleError);
}
return this.accountObservable;
}
Run Code Online (Sandbox Code Playgroud)
我在我的bootstrap函数中添加了该服务以在全局范围内提供它(我希望为所有组件提供相同的实例):
provide(AccountService, { useClass: AccountService })
Run Code Online (Sandbox Code Playgroud)
问题是当我在不同的组件中调用此服务时,每次都会发出GET请求.因此,如果我将其添加到3个组件,即使我检查是否已存在可观察量,也会发出3个GET请求.
ngOnInit() {
this._accountService.getAccount().subscribe(
account => this.account = account,
error => this.errorMessage = <any>error
);
}
Run Code Online (Sandbox Code Playgroud)
如何防止多次发出GET请求?
Mar*_*cok 21
if (this.accountObservable === null) {
this.accountObservable = this._http.get('./data/data.json')
.share()
.map(res => res.json())
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
在Plunker中,AppComponent和Component2都调用了getAccount().subscribe()两次.
借助share()Chrome Developer工具网络标签,可以显示一个HTTP请求data.json.随着share()注释掉,有4个请求.
| 归档时间: |
|
| 查看次数: |
15320 次 |
| 最近记录: |