Http request made multiple times in Angular2 service

后端 未结 4 689
-上瘾入骨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:25

    The updated solution is:

    1) Change your getAccount() method to use share:

    getAccount () {
        // If we have account cached, use it instead
        if (this.accountObservable === null) {
            this.accountObservable = this._http.get('http://localhost/api/account')
                .pipe(share())
                .map(res =>  res.json().data)
                .catch(this.handleError);
        }
    
        return this.accountObservable;
    }
    

    2) Add import { share } from 'rxjs/operators'; to the top of your .ts file to get rid of the error on share.

提交回复
热议问题