Fah*_*san 2 typescript angular-routing angular angular-route-guards
我有一个 Angular 7 应用程序,其中有一条像这样的路线
{ path : 'forgot-password/:resetHash/:email',
component : ForgotPasswordComponent,
canActivate : [ForgotPasswordPageGuard]},
Run Code Online (Sandbox Code Playgroud)
现在我尝试访问该路由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;
}
}
Run Code Online (Sandbox Code Playgroud)
但它给出了这个错误
我究竟做错了什么?
canActivate将其ActivatedRouteSnapshot作为第一个参数,因此将其添加到您的函数中。
export class MyGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot): boolean => {
const email = route.paramMap.get('email');
// the rest of the implementation
}
}
Run Code Online (Sandbox Code Playgroud)
CanActivate文档中的界面
interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
}
Run Code Online (Sandbox Code Playgroud)
编辑
如果你想在你的守卫内部发出 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)
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3197 次 |
| 最近记录: |