订阅方法中的Angular 2函数甚至在完成或请求之前被调用

时间:2017-07-31 06:34:54

标签: angular angular2-routing

我正在尝试从URL获取参数,然后将其传递给另一个方法。这是代码:

 ngOnInit() {
    this.getParamValues();
  }

 getParamValues() {
    this.route.queryParams.subscribe(params => {      
        this.checkUser(params);
    });
  }



  checkUser(params: any) {  
// Here this method i called twice first time with no params and second time with params
  }

此检查方法将首先检查基本上是否检查会话存储中的用户是否从其他地方加载基本详细信息进入服务。

所以问题是我的checkUser方法被调用了两次,我只是无法检查params是否为空,因为除了这个逻辑之外我还有其他事情要做。

我的check用户方法是否可能仅在使用以前的数据完成订阅方法时才被调用?

由于

2 个答案:

答案 0 :(得分:3)

getParamValues() {
  this.route.queryParams.subscribe(params => {
    if (params) {
      this.checkUser(params);
    }
  });
}



checkUser(params: any) {  

}

<强>更新

ngOnInit(){
  if(localStrorage.getItem('User')){
    // get user details
  } else {
    getParamValues();
  }
}

答案 1 :(得分:0)

所以我并不完全确定我理解你的问题 - 你无法检查参数,但是你可以在没有参数的情况下运行checkuser函数吗?为什么不:

getParamValues() {
  this.route.queryParams.subscribe(params => {
    if (params) {
      this.checkUser(params);
    }
    // Other logic here
  });
}

或者,如果您需要运行checkUser,无论如何:

checkUser(params: any) {  
  if (params) { ... } else { ... }
}