Angular 激活问题TS2720

Angular 激活问题TS2720,angular,Angular,我对CanActivate有意见 import { AuthService } from './auth.service'; import { CanActivate } from '@angular/router/src/utils/preactivation'; import { ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { Observable } from

我对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']);
        }
    }
}
从“/auth.service”导入{AuthService};
从“@angular/router/src/utils/preactivation”导入{CanActivate};
从'@angular/Router'导入{ActivatedRouteSnapshot,RouterStateSnashot,Router};
从“rxjs”导入{Observable};
从“@angular/core”导入{Injectable};
@可注射()
导出类AuthGuard实现了CanActivate{
构造函数(私有authService:authService,
专用路由器(路由器)
{
}
canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot)
:可观察的|承诺|布尔值{
if(this.authService.isAuth){
返回true;
}否则{
this.router.navigate(['/auth']);
}
}
}
它告诉我:

src/app/services/auth guard.service.ts(10,14)中出错:错误TS2720: 类“AuthGuard”不正确地实现了类“CanActivate”。是吗 是否要扩展“可以激活”并将其成员作为子类继承?
类型“AuthGuard”缺少类型中的以下属性 “CanActivate”:路径、路线

但我不明白为什么


非常感谢大家

您从错误的位置导入了
CanActivate
接口。应该是

从'@angular/router'导入{CanActivate}


else
语句中
返回false
也是一个好主意。

您可能启用了
strict
。您的函数指定返回类型:
Observable | Promise | boolean
,但您不会从else分支返回任何内容。这意味着您的返回类型是
true |未定义
布尔型|未定义
。您必须从else分支返回某些内容:

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;
        }
    }
从'rxjs'导入{可观察,空}
//等等
canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot)
:可观察的|承诺|布尔值{
if(this.authService.isAuth){
返回true;
}否则{
this.router.navigate(['/auth']);
返回空;
}
}

就我而言,我提供的是一个粗心的错误

        canActivate: AuthGuard,
而不是

        canActivate: [AuthGuard],

请注意方括号

非常感谢^^没问题。很高兴我能帮上忙:)你能通过点击左边的复选标记将问题标记为已回答:)谢谢你的帮助,但它只是在错误的导入文件夹中被激活了。:)