【问题标题】:on change route need to run a function to check the token在更改路线时需要运行一个函数来检查令牌
【发布时间】:2017-10-24 23:53:46
【问题描述】:

在 Angular 中,对于每条已更改的路由,如果设置了有效令牌,我都需要运行该函数。

谁能帮我做这个?

在 Angular 1 中,我经常使用 $on

【问题讨论】:

标签: javascript angular typescript angular2-routing


【解决方案1】:

您可以使用CanActivate来保护路由或在路由转换过程中调用函数,示例如下

import { Router, CanActivate } from '@angular/router';

export class AuthGuard implements CanActivate {

constructor(private router: Router) { }

canActivate() {
  return true //or false
}
}

官方doc

更新步骤

  1. 如上代码所述编写 AuthGuard 服务
  2. 在提供程序(app.module.ts 文件)中添加 AuthGaurd
  3. 以这种方式,只要发生转换,就会调用 canActivate。

假设

  1. 您已经在 appModule 中注册了路由

教程

  1. http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial

【讨论】:

  • 自从我今天开始,我知道我在问愚蠢的事情,但是你能告诉我在哪里更新代码意味着在哪个文件中,因为我需要检查每条路线的变化
  • 请查看更新后的答案,欢迎再次提问。如果您认为正确,请接受答案。
猜你喜欢
  • 2015-06-22
  • 1970-01-01
  • 2020-08-07
  • 2022-01-07
  • 1970-01-01
  • 2014-07-20
  • 2021-04-05
  • 2012-02-23
  • 1970-01-01
相关资源
最近更新 更多