【问题标题】:router.navigate() doesn't redirect inside .subscriberouter.navigate() 不会在 .subscribe 内重定向
【发布时间】:2018-09-21 14:07:08
【问题描述】:

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

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']));

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

【问题讨论】:

  • navigate 返回一个 Promise,您将忽略它。它可能会返回false 或拒绝。考虑处理Promise 以排除这些可能性。
  • 谢谢,我现在就试试!
  • this.router.navigate(['app']).then(x =&gt; console.log(x)); 只返回false,一定是这样。任何建议@Alex Peters
  • 可能值得将应用的路由模块粘贴到问题中,以防另一双眼睛可以发现那里的任何小问题。
  • @Alex Peters,我几乎可以肯定这是我的 auth gaurd,你帮我想出了一个解决方案。谢谢

标签: angular rxjs angular6 router


【解决方案1】:

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;
    }        
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多