简体   繁体   English

如何在Angular2中实现CanActivate Guard

[英]How to implement CanActivate guard in Angular2

I am trying to implement "CanActivate" method in my service, and below is the service code 我正在尝试在我的服务中实现“ CanActivate”方法,以下是服务代码

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable()
export class GuardUserSearchService implements CanActivate {

    CanActivate() {
        console.log('dummy guard clause for User search');
        return true;
    }
}

When I compile this typeScript code , it is displays following error 当我编译此typeScript代码时,它显示以下错误

Class 'GuardUserSearchService' incorrectly implements interface 'CanActivate'. 类“ GuardUserSearchService”错误地实现了接口“ CanActivate”。

Any idea what is the issue in my code. 知道我的代码有什么问题。

Your Service must implement this function to fully implement that CanActivate interface: 您的服务必须实现此功能才能完全实现该CanActivate接口:

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean { }

Note that the interface name is CanActivate (with uppercase C ) while method's name is canActivate (lowercase c ). 请注意,接口名称为CanActivate (大写C ),而方法名称为canActivate (小写c )。

As per the documentation , the interface looks like this: 根据文档 ,界面如下所示:

interface CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean>|Promise<boolean>|boolean
}

So, your implementation is missing the arguments: 因此,您的实现缺少参数:

export class GuardUserSearchService implements CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        console.log('dummy guard clause for User search');
        return true;
    }
}

just one change required- 只需一项更改-

#both C&A is capital
export class Guard implements CanActivate () {
-code-
}

#here only A is in capital dont follow CammelCase
canActivate(){ 
-code
});

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

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