网站搜索

angular - 在 canActivate 上结束 return 语句的问题


当我使用 CanActivate 方法时,我遇到了一个问题:出现错误 ts2366 “函数缺少结束返回语句且返回类型不包含 undefined”。

按照我的代码:

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']);
    }
  }
}

我尝试在 boolean 后添加 '| undefined',但另一个错误告诉我它与 CanActivate 不兼容。

你有任何解决它的办法吗?

提前感谢您的帮助。

答案#1

您应该从 canActivate 返回 boolean 或 UrlTree。如果您返回 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');
    }
  }
}