简体   繁体   English

node / angular2服务将值返回错误的组件

[英]node/angular2 services returning values to wrong component

I am new to nodejs/angular2. 我是nodejs / angular2的新手。 I am having a strange issue with Async behavior of node and its return to an angular service. 我在节点的异步行为及其返回到角度服务时遇到了一个奇怪的问题。 The issue I am having is two different angular components say component A and component B have the same angular service injected in them. 我遇到的问题是两个不同的角度分量,也就是说,分量A和分量B注入了相同的角度服务。

The server side is an async node server which takes some time to complete the request.The problem is when the app routes from angular component A to angular component B, sometimes the request to node completes from component A but since we are currently routed to component B the response goes there. 服务器端是一个异步节点服务器,需要花费一些时间来完成请求。问题是当应用程序从角度组件A路由到角度组件B时,有时到节点的请求已从组件A完成,但是由于我们当前已路由到组件B响应到达那里。 (Component A and B are not visible at the same time. Only one is visible at a time) (组件A和B不能同时显示。一次只能看到一个)

Because component B is also subscribed to the same service/method it will get the return result that was designated for component A. Resulting in incorrect values. 由于组件B也订阅了相同的服务/方法,因此它将获得为组件A指定的返回结果。导致值不正确。

Is there a way from Component B to only receive the responses to the requests it sent out. 组件B是否有办法仅接收对其发出的请求的响应。

Both are components are subscribed to the same method within the service as such: 这两个组件都在服务中订阅了相同的方法,如下所示:

The code is way to big to put on here so I am going to do snippets. 代码很大,可以放在这里,所以我将做一些片段。

Here is the code that is in each component. 这是每个组件中的代码。

getNode(){

    this.userService.getNode().subscribe(resNodeData => {
    this.node = resNodeData; 
            if(this.node == null){
            return null;
        }
        else{
     // console.log(this.node);  
            }
        });

} }

Code from Service Layer: 来自服务层的代码:

export class UserService {
  //call to node server async
 getNode() {
return this.http.get("http://" + host + ":3000/api/namenode/"  + this.clusterService.getCluster())
.map((res:Response) => res.json())
.catch(this._errorHandler);
  }


 }

I know my question is long and confusing. 我知道我的问题很长且令人困惑。 I would appreciate any help. 我将不胜感激任何帮助。

您需要在生命周期挂钩OnDestroy中退订这两个组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM