Below is my implementation of CanActivate guard clause in TypeScript , when I compile this code , it shows below error
A function whose declared type is neither 'void' nor 'any' must return a value
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean {
this.appService.isValidUser().subscribe({
next: (data) => data.authenticated, // this return true or false
error: (err) => false
});
}
What is the reason for this error ?
canActivate
should return an Observable
not a Subscription
. If you call .subscribe()
, you'll get a Subscription
, therefore we use .map()
.
To handle the error case use .catch()
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> {
return this.appService.isValidUser()
.map(data => data.authenticated)
.catch(_ => Observable.of([false]));
}
Don't forget to import all operators
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.