简体   繁体   English

angular2在AuthGuard中实现接口

[英]angular2 implements interface within AuthGuard

I try to implement auth guard protection to my app, here is my code: 我尝试对我的应用程序实施身份验证保护,这是我的代码:

import {Injectable} from '@angular/core'
import {Router, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router'
import {CanActivate} from '@angular/router'
import {Auth} from './services/auth.service'

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private auth:Auth, private router:Router){

    }
    CanActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot){
        if(this.auth.authenticated()){
        console.log("AUTH GUARD LET GO");
        return true;
        }
        else{
            console.log("BLOCKED BY AUTH GUARD");
            this.router.navigate(['/']);
            return false;
        }
    }
}

and the error message: 和错误消息:

[ts] Class 'AuthGuard' incorrectly implements interface 'CanActivate'. [ts]类“ AuthGuard”错误地实现了接口“ CanActivate”。 Property 'canActivate' is missing in type 'AuthGuard'. 类型“ AuthGuard”中缺少属性“ canActivate”。

I make search on net but couldnt find any valuable information please help me if you have come across with this kind of issue and solved or any idea you got about it.. 我在网上搜索,但是找不到任何有价值的信息,如果您遇到这种问题并已解决,或者对它有任何想法,请给我帮助。

The error is saying your app can't find the correct function to use for can activate. 错误是您的应用无法找到用于激活的正确功能。 The canActivate function name is camelCase, try canActivate函数名称是camelCase,请尝试

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    //logic
}

This problem sometimes happen when you import from wrong libraries. 从错误的库导入时,有时会出现此问题。 Check the import statement. 检查导入语句。 Change 更改
import { CanActivate } from'@angular/router/src/utils/preactivation';
to
import { CanActivate } from '@angular/router';

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM