2017-03-22 55 views
0

我的服務第一次運作良好。當它再次被調用時,它不起作用。我在NgModule如何在一個組件中訂閱Angular 2中的服務幾次?

服務這裏是我的代碼

this._portService.getPortList().subscribe(
     (data) => { 
      this.len = data['interfaces-state'].length; 
       for (this.i = 0; this.i<this.len;this.i++){ 
        this.portListJson.push(data['interfaces-state'][this.i].interface); 
        } 
       this.removeONUPorts(); 
       this.addNames(); 
       }); 

我的構造

constructor(private _portService:PortsService, private elRef: ElementRef){ 
     } 

當我嘗試調用不同的功能不起作用相同的代碼。

我的服務

getPortList(){ 
    return this._http.get(environment.api + "restconf/data/ietf-interfaces:interfaces-state/interface?fields=") 
    .map(response => response.json()); 
}; 

我的第二個電話

setONUList(port: Port){ 
     this.clearLists(); 
     this._portService.getPortList().subscribe(
      (data) => { 
       this.len = data['interfaces-state'].length; 
        for (this.i = 0; this.i<this.len;this.i++){ 
         this.portListJson.push(data['interfaces-state'][this.i].interface); 
         } 
         this.removeONUPorts(); 
         this.addNames(); 
        }); 

} 
+0

更新問題與您的第二次訂閱現在它似乎很好 –

+0

你是否在getPortList()中調用正確的URL。您可以查看通過安裝返回的數據。像嘗試這樣來檢查:'getPortList(){ 返回this._http.get(environment.api +「restconf/data/ietf-interfaces:interfaces-state/interface?fields =」) .map(response => response 。上傳.json())做(數據=>的console.log(JSON.stringify(數據))); };' –

+0

我做了,它不訂閱。在調試時跳過那部分 – Erad

回答

0

我不知道你要在這裏完成的。我不明白你爲什麼需要來自同一個組件的2個訂閱。通常我在組件的構造函數或ngOnInit方法中實例化我的訂閱,然後將訂閱中的值映射到組件中的本地值,然後可以使用任何組件方法訪問該值。

所以我會做這樣的事情:

 this._portService.getPortList().subscribe(
      (data) => { 
         this.localDataVar = data; 
         ... 
        }); 

然後在您的組件的方法,你可以訪問你的localDataVar變量

setONUList(port: Port){ 
     this.clearLists(); 
     this.someFunction(this.localDataVar); //here you'll have last emitted value of data 
} 

或者另一種方式是簡單地在訪問當前觀測的值的後續方法是這樣的:

setONUList(port: Port){ 
     this.clearLists(); 
     let curVal = this._portService.getPortList().getValue(); 
} 

我不明白爲什麼喲你需要或希望來自同一個組件的兩個相同的訂閱。

+0

我需要它,因爲我需要刷新按鈕 – Erad

+0

,這並不意味着您需要兩個訂閱。您只需要一個,並更新訂閱發佈的值的方法。 – cobolstinks

+0

現在它根本不會被調用 – Erad

相關問題