2016-05-05 22 views
2

我在想我的代码有什么问题。我在我的服务如下:Http流发送两次而不是一次

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网络和debuggin看,似乎是:

this._http.get('someApi') 

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

我错过了什么?

回答

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' 
+0

是有那么一种方法来在地图方法内赶上错误? – uksz

+0

我解答了我的答案。 –

+1

一如既往有帮助。谢了哥们! – uksz