2
votes

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 ?

1

1 Answers

4
votes

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';