【问题标题】:Calling angular2 route guard multiple times多次调用 angular2 路由保护
【发布时间】:2016-11-19 11:44:52
【问题描述】:

我的一条私有路由上有一个路由守卫,当守卫返回 false 时,它​​不再被调用。下面的例子简化了如何重现这种情况。

当用户使用链接导航时:

<a [routerLink]="['my-private-route']">Link</a>

守卫被调用,我在控制台中看到called 消息并且导航被取消(我在守卫中返回false):

@Injectable()
export class CanActivateViaAuthGuard implements CanActivate {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean {
    console.log('called')
    return false;
  }
}

但是,当用户再次点击链接时,什么也没有发生。

为什么我需要这种行为?我需要重复调​​用警卫的原因是因为我必须显示模态Do you want to login? YES/NO。当用户点击no 我想留在页面上。但是当他后来决定再次导航时,我想让他再次登录。

有什么方法可以阻止 angular2 缓存保护结果?

【问题讨论】:

  • 请提供 Plunker 进行复制。我希望这也能奏效。
  • @GünterZöchbauer 很有趣。我做了那个 plunker,它确实在那里工作。 plnkr.co/edit/17CBn14zPuyrAhVnS4pA 我将调查我的代码有何不同。谢谢:-)
  • @GünterZöchbauer 区别在于 Angular 2.2.0 和 2.1.2。看起来这个保护缓存出现在 2.2.0 中。
  • 我会将其报告为错误。这对我来说没有意义。每次都需要重新评估守卫。

标签: angular angular2-routing angular2-guards


【解决方案1】:

经过@GünterZöchbauer 的一些调查和帮助,这是角度路由器 3.2.0 的一种奇怪行为。已经有类似问题:https://github.com/angular/angular/issues/12851

Here is plunker with 3.1.2 where guard is evaluated every time:

https://plnkr.co/edit/jUhVJY?p=preview

Here is plunker with 3.2.0 where guard is evaluated only once:

https://plnkr.co/edit/2A0Wfu?p=preview

【讨论】:

  • 这个问题在 Angular 4 中修复了吗?
  • @Anthony 是的。它已在下一个补丁版本中得到修复。
【解决方案2】:

我遇到了同样的问题。看起来该行为可以在 4.x 中被覆盖:

https://angular.io/api/router/Routes

检查 runGuardsAndResolvers 路由参数。

我还错误地认为路由器 3.4.x 中会使用值“always”

【讨论】:

  • 你是如何实现的?添加“runGuardsAndResolvers:'always'”似乎没有任何作用。 canDeactivate 守卫仍然只被调用一次。
猜你喜欢
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 2019-02-10
  • 2020-12-19
相关资源
最近更新 更多