Http请求在Angular2服务进行多次 [英] Http request made multiple times in Angular2 service

查看:472
本文介绍了Http请求在Angular2服务进行多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个服务,使一个简单的GET请求:

I have created a service that makes a simple GET request:

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;
}

我补充说,在我的引导功能,服务于全球提供它(我的希望是为同一个实例的所有组件):

I have added that service in my bootstrap function to provide it globally (my hope is to provide the same instance to all components):

provide(AccountService, { useClass: AccountService })

问题是,当我调用不同的组件该服务,GET请求时每次。所以,如果我把它添加到3个组成部分,3 GET请求将作出,即使我检查是否可观察到已经存在。

The problem is when I call this service in different components, a GET request is made every time. So if I add it to 3 components, 3 GET requests will be made even though I check if an observable already exist.

ngOnInit() {
  this._accountService.getAccount().subscribe(
    account => this.account = account,
    error =>  this.errorMessage = <any>error
  );
}

我如何prevent GET请求来进行多次?

How can I prevent the GET request to be made multiple times?

推荐答案

使用的 Observable.share()

if (this.accountObservable === null) {
    this.accountObservable = this._http.get('./data/data.json')
      .share()
      .map(res => res.json())
      .catch(this.handleError);
}

<大骨节病> Plunker

在Plunker,AppComponent和COMPONENT2双方通话是getAccount()。认购()两次。

In the Plunker, AppComponent and Component2 both call getAccount().subscribe() twice.

使用份额(),Chrome开发者工具Network标签显示为 data.json 的HTTP请求。随着份额()注释掉,有4个请求。

With share(), the Chrome Developer tools Network tab shows one HTTP request for data.json. With share() commented out, there are 4 requests.

这篇关于Http请求在Angular2服务进行多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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