Error in canActivate guard method

Below is my implementation of the CanActivate protection proposal in TypeScript, when I compile this code it shows below error

A function whose declared type is neither void nor any should 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?

+2
source share
1 answer

canActivate should return Observable not a Subscription . If you call .subscribe() you will get a Subscription , so we use .map() .

To handle the error, use .catch()

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> { return this.appService.isValidUser() .map(data => data.authenticated) .catch(_ => Observable.of([false])); } 

Do not forget to import all operators

 import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import "rxjs/add/observable/of"; 
+3
source

Source: https://habr.com/ru/post/1264911/


All Articles