无法解析AuthGuard的所有参数:在我的AuthGuard服务中

问题描述 投票:4回答:1

我有一个AuthGuard.service.ts的代码如下。

import { Injectable } from '@angular/core';
import { ActivatedRoute, CanActivate } from '@angular/router';
import { userLoginService } from './userLoginService';
export class AuthGuard implements CanActivate {
    constructor(private service: userLoginService) { }
    canActivate() {
        if (this.service.IsloggedIn()) {
            return true;
        } else {
            window.alert(' You are not logged in.Please LogIn ');
            return false;
        }
    }

}

在userLoginService.ts中,我有如下代码

export class userLoginService {
    constructor() {}
    IsloggedIn(): boolean {
        return false;
    }
}

我在我的路线中注入了这个AuthGuard.service.ts,如下所示。我还在NgModule的提供者中提供了这个服务名称。

    const appRoutes: Routes = [
      { path: '', component: HomePageComponent, pathMatch: 'full' },
      { path: 'CartItems', component: CartItemsComponent, pathMatch: 'full', canActivate: [ AuthGuard ]},
    ];
@NgModule({
.
.
.
 providers: [UserInfoService , AuthGuard],
.
.
.

现在执行此代码时,我收到如下错误。

Uncaught Error: Can't resolve all parameters for AuthGuard: (?).
    at syntaxError (compiler.js:466)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15547)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15382)
    at CompileMetadataResolver._getInjectableMetadata (compiler.js:15362)
    at CompileMetadataResolver.getProviderMetadata (compiler.js:15722)
    at eval (compiler.js:15633)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15593)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15161)
    at JitCompiler._loadModules (compiler.js:33542)

你能不能让我知道我犯了什么错误。

angular routing angular5 auth-guard
1个回答
18
投票

我看到你导入Injectable但你永远不会使用它!

在您的AuthGuard.service.ts中。你应该在你的班级上面添加:@Injectable(),如:

@Injectable()
export class AuthGuard implements CanActivate {
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.