router.navigate()不在.subscribe

时间:2018-09-21 14:07:09

标签: angular rxjs angular6 router

我有这样的登录功能:

login() {

// clear error text
this.state.errorText = "";

// try to login
this.sb.login(this.model.username, this.model.password).subscribe(x => {
  // check if ok
  if(x.success) {
    console.log('does this print') //<-- outputs as expected
    this.router.navigate(['/app']); 
  } else {
    this.state.errorText = x.response;
  }        
});

通过调试器,我可以看到x.success返回为true。我的console.log可以打印,但是之后,this.router.navigate(...)行似乎什么也没做。没有重定向。

我尝试使用:

this.zone.run(() => this.router.navigate(['/app']));

但是结果相同,没有页面重定向。

1 个答案:

答案 0 :(得分:0)

1在本地分配路由服务 2使用分配的本地服务

login() {
  this.state.errorText = "";
  var route = this.router; // Assign router locally 

  // try to login
  this.sb.login(this.model.username, this.model.password).subscribe(x => {
    // check if ok
    if (x.success) {
      console.log('does this print') //<-- outputs as expected
      route.navigate(['/app']); // use local route service
    } else {
      this.state.errorText = x.response;
    }        
  });
}