router.navigate() 不会在 .subscribe 内重定向

gho*_*oul 5 router rxjs angular angular6

我有一个像这样的登录功能:

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;
    }        
  });
}
Run Code Online (Sandbox Code Playgroud)

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

我尝试过使用:

this.zone.run(() => this.router.navigate(['/app']));
Run Code Online (Sandbox Code Playgroud)

但这会导致相同的结果,没有页面重定向。

小智 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;
    }        
  });
}
Run Code Online (Sandbox Code Playgroud)