Http流发送两次而不是一次

时间:2016-05-05 11:49:47

标签: angular rxjs

我想知道我的代码有什么问题。我的服务中有以下内容:

updateCollection(){
    var updateStream = this._http.get('someApi')
        .map((res)=>{
            return res.json();
        })

    updateStream.subscribe(
        success=> {
            this.collection.length = 0;
            console.log('Success in getting collection: ', success.collection);
            (<any>Object).assign(this.collection, success.collection);
            return this.collection;
        }
    );

    return updateStream;
}

getCollection(){
    return this.updateCollection();
}

在我的组件中,我定义了:

this._service.getCollection()
        .subcribe(
            success=>{
                console.log("In component", success)
            }
)

但是,正如我从Chrome网络和调试程序中看到的那样,似乎:

this._http.get('someApi')

被调用两次,而不是一次。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

那是因为你subscribe()两次。进入updateCollection()后进入getCollection()

这应该做你想要的:

updateCollection(){
    return this._http.get('someApi')
        .map((res)=>{
           let result = res.json();
           this.collection.length = 0;
           console.log('Success in getting collection: ', success.collection);
            (<any>Object).assign(this.collection, success.collection);
           return result;
        })
        .catch(error => {
          console.log(error);
          return Observable.of([]); to silently continue
          // or return Observable.throw(error);
          // or just throw error;
        });
}

确保您已导入所有内容

import 'rxjs'

import 'rxjs/add/observable/of'
import 'rxjs/add/operator/catch'