error in canActivate guard method

天大地大妈咪最大 提交于 2020-01-24 12:34:19

问题


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:


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


来源:https://stackoverflow.com/questions/41911094/error-in-canactivate-guard-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!