Http request made multiple times in Angular2 service

后端 未结 4 691
-上瘾入骨i
-上瘾入骨i 2021-01-01 21:39

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

private accountObservable = null;

constructor(private _http: Http) {
}

getAccount () {
    // If          


        
4条回答
  •  情深已故
    2021-01-01 22:27

    There are two types of observables.

    Cold Observable : each subscriber receive all the events ( from the begining )

    Hot observable : each subscriber receive the events that are emited after subscription.

    Cold Observables are the default one. That's what the WS calling is triggered many times.

    To make an Observable Hot you have to use following Rx's operators chain :

    .publish().refCount()
    

    In your case :

    getAccount () {
    
        let accountObservable = this._http.get('http://localhost/api/account')
                .map(res =>  res.json().data)
                .catch(this.handleError);
    
        return accountObservable.publish().refCount();
    }
    

提交回复
热议问题