【问题标题】:How to access route params in route guard clause in Angular 7?如何在 Angular 7 的路由保护子句中访问路由参数?
【发布时间】:2020-02-27 03:33:32
【问题描述】:

我有一个 Angular 7 应用程序,其中我有这样的路线

{ path : 'forgot-password/:resetHash/:email', 
  component : ForgotPasswordComponent, 
  canActivate : [ForgotPasswordPageGuard]},

现在我尝试访问这条路由的params,它是route-guard,但我没有得到路由参数。这是我的forgotpassword.route.guard.ts

constructor(private _utilityService: UtilitySerivce, private _dataService: DataService, private _const: Constants, private _router: ActivatedRouteSnapshot) {
}

canActivate = (): boolean => {
    console.log('in link expiry guard')
    let userEmail = this._router.paramMap.get('email');
    let isAllow = false;

    console.log('params : ', userEmail)
    userEmail = this._utilityService.decryptMsgByCryptoJs(userEmail);
    console.log('user email : ', userEmail)
    this._dataService.post(this._const.userResetPasswordLinkExpiry, { email: userEmail }).subscribe(resp => {
        if (resp.success) {
            isAllow = true;
        } else {
            isAllow = false;
        }
    })
    if (isAllow) {
        return true;
    } else {
        this._utilityService.navigate('/login');
        this._dataService.exhangeResetPasswordObsMsg({ event: 'linkExpired' });
        return false;
    }
}

但它给出了这个错误

我做错了什么?

【问题讨论】:

  • 错字警告:这是一个守卫 - 而不是“守卫” ....

标签: angular typescript angular-routing angular-route-guards


【解决方案1】:

canActivateActivatedRouteSnapshot 作为其第一个参数,因此请将其添加到您的函数中。

export class MyGuard implements CanActivate {
  canActivate(route: ActivatedRouteSnapshot): boolean => {
    const email = route.paramMap.get('email');

    // the rest of the implementation
  }
}

CanActivate 接口来自the docs

interface CanActivate {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): 
    Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
}

编辑

如果你想在你的守卫内部发出一个 HTTP 请求,你可以返回 Observable&lt;boolean&gt;。从界面可以看出这是允许的。

export class MyGuard implements CanActivate {
  constructor(private http: HttpClient) {}

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> => {
    const email = route.paramMap.get('email');

    return this.http.get('some url').pipe(
      // map response to some boolean value that determines the permission
      map((response): boolean => true)
    );
  }
}


【讨论】:

  • 当我使用 RouterStateSnapshot 所以它给出了这样的错误 NullInjectorError: No provider for ActivatedRouteSnapshot!
  • 你导入路由模块了吗?
  • 是的,我在我的 app.module.ts 中导入了 RouterModule,我收到了这个错误 ibb.co/pJkCDr8
  • 如果您只想获取参数,则不需要路由器状态快照。
  • 我没明白你的意思。当我使用ActivatedRoute 所以你说canActivate 只使用ActivatedRouteSnapshot 现在你说你不需要使用这个?你想说什么?请在你的回答中澄清
猜你喜欢
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多