canActivate上结束return语句的问题

问题描述

我在使用 CanActivate 方法时遇到问题:出现错误 ts2366“函数缺少结束返回语句且返回类型不包含未定义”。

遵循我的代码

import { ActivatedRouteSnapshot,CanActivate,Router,RouterStateSnapshot,UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,private router: Router) { }

  canActivate(
    route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.isAuth) {
      return true;
    } else {
      this.router.navigate(['/auth']);
    }
  }
}

我尝试添加'|布尔值后未定义',但另一个错误告诉我它与 CanActivate 不兼容。

你有什么解决办法吗?

提前感谢您的帮助。

解决方法

您应该从 boolean 返回 UrlTreecanActivate。如果您返回 UrlTree,它将为您处理导航,因此您无需自己调用 this.router.navigate(请参阅 https://angular.io/api/router/CanActivate

您的代码可能如下所示:

import { ActivatedRouteSnapshot,CanActivate,Router,RouterStateSnapshot,UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,private router: Router) { }

  canActivate(
    route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.isAuth) {
      return true;
    } else {
      return this.router.parseUrl('/auth');
    }
  }
}