If you want to make an Http request inside your canActivate
function, you need to return an Observable<boolean>
instead of a boolean
, since you are now performing an asynchronous action.
And since you want to navigate on fail, you should return Observable<boolean | UrlTree>
instead.
Simple version
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> {
return this.http.post(url, body).pipe(
map((resp: any) => resp.success ? true : this.router.parseUrl('/path'))
);
}
We are returning the observable http request (the router will invoke it by subscribing), and mapping the response to either a
true
- the router may proceed to the guarded route
UrlTree
- the router should navigate to the route we have returned
Applied to your example
If we apply this to your example, we need to do a bit more work in the pipe, as you have an additional service call.
// TODO: inject other services
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> {
const userEmail = route.paramMap.get('email');
// I am assuming this is a synchronous call
userEmail = this._utilityService.decryptMsgByCryptoJs(userEmail);
const url = this._const.userResetPasswordLinkExpiry;
const body = { email: userEmail };
return this._dataService.post(url, body).pipe(
// initial map from response to true/false
map((resp: any) => resp.success),
// perform an action if false
tap(success => {
if (!success) {
// I'm assuming this is synchronous. If not, you will need to do a switchMap
this._dataService.exhangeResetPasswordObsMsg({ event: 'linkExpired' });
}
}),
// final map to boolean | UrlTree
map(success => success ? true : this.router.parseUrl('/login'))
);
}
There are some service calls in there that I'm assuming are synchronous. This answer demonstrates how you perform an asynchronous call inside canActivate
and either allow the router to navigate or return an alternative route to navigate to.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…