我在使用 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']);
}
}
}
我尝试添加“|” bool 值后未定义',但另一个错误告诉我它与 CanActivate 不兼容。
你有什么办法解决这个问题吗?
预先感谢您的帮助。
最佳答案
您应该从 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');
}
}
}
关于angular - canActivate 上结束 return 语句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67093083/