在Angular2服务中多次发出Http请求

Chr*_*fer 13 http angular

我创建了一个发出简单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

用途Observable.share():

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

在Plunker中,AppComponent和Component2都调用了getAccount().subscribe()两次.

借助share()Chrome Developer工具网络标签,可以显示一个HTTP请求data.json.随着share()注释掉,有4个请求.

  • 这不起作用.一段时间看到这个问题,而这个解决方案,再次看到它,解决方案仍然无法正常工作. (7认同)
  • 在较新的 rxjs 上,您需要使用 `pipe`,因此需要更新为:`.get(...).pipe(share(), map(...))`。来源:https://www.learnrxjs.io/operators/multicasting/share.html (2认同)