2

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

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

现在我试图访问这条路线paramsroute-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;
    }
}

但它给出了这个错误

在此处输入图像描述

我究竟做错了什么?

4

1 回答 1

7

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

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

    // the rest of the implementation
  }
}

CanActivate来自文档的界面

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

编辑

如果你想在你的守卫内部发出一个 HTTP 请求,你可以返回Observable<boolean>。您可以从界面中看到这是允许的。

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


于 2020-02-24T18:59:57.790 回答