我创建了一个发出简单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; }
我在我的bootstrap函数中添加了该服务以全局提供它(我希望为所有组件提供相同的实例):
provide(AccountService,{ useClass: AccountService })
问题是当我在不同的组件中调用此服务时,每次都会发出GET请求.因此,如果我将其添加到3个组件,即使我检查是否已存在可观察量,也会发出3个GET请求.
ngOnInit() { this._accountService.getAccount().subscribe( account => this.account = account,error => this.errorMessage = <any>error ); }
如何防止多次发出GET请求?
使用
Observable.share()
:
if (this.accountObservable === null) { this.accountObservable = this._http.get('./data/data.json') .share() .map(res => res.json()) .catch(this.handleError); }
在Plunker中,AppComponent和Component2都调用getAccount().subscribe()两次.
使用share(),Chrome开发人员工具“网络”标签会显示一个针对data.json的HTTP请求.随着share()被注释掉,有4个请求.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。