2017-03-22 68 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