gpt4 book ai didi

angular - 如何在 Angular 7 的路由保护子句中访问路由参数?

转载 作者:行者123 更新时间:2023-12-05 09:11:13 28 4
gpt4 key购买 nike

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

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

现在我尝试在 route-guard 中访问此路由的 params 但我没有在 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;
}
}

但它给出了这个错误

enter image description here

我做错了什么?

最佳答案

canActivate需要 ActivatedRouteSnapshot作为它的第一个参数,所以将其添加到您的函数中。

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


关于angular - 如何在 Angular 7 的路由保护子句中访问路由参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60382311/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com