我在CanActivate上有个问题
import { AuthService } from './auth.service';
import { CanActivate } from '@angular/router/src/utils/preactivation';
import { ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
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']);
}
}
}它告诉我:
src/app/services/auth-guard.service.ts(10,14):ERROR TS2720中的错误:类'AuthGuard‘不正确地实现类'CanActivate’。您的意思是作为子类扩展‘能激活’并继承其成员吗? 类型“AuthGuard”缺少“CanActivate”类型中的下列属性:路径、路由
但我不明白为什么?
非常感谢大家!
发布于 2019-01-21 14:36:33
您从错误的位置导入了CanActivate接口。它应该是
import { CanActivate } from '@angular/router';
在return false语句中使用else也是个好主意。
发布于 2019-01-21 14:46:09
可能已经启用了strict。您的函数指定了返回类型:Observable<boolean> | Promise<boolean> | boolean,但是您没有从return分支返回任何内容。也就是说,您的返回类型是true | undefined或boolean | undefined。你必须从其他分支退回一些东西:
import { Observable, EMPTY } from 'rxjs'
// and so on
canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot )
: Observable<boolean> | Promise<boolean> |boolean {
if (this.authService.isAuth) {
return true;
}else{
this.router.navigate(['/auth']);
return EMPTY;
}
}发布于 2019-10-12 10:54:40
在我的例子中,我提供的是一个粗心的错误。
canActivate: AuthGuard,而不是
canActivate: [AuthGuard],注意方括号
https://stackoverflow.com/questions/54292142
复制相似问题