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

roo*_*eja 5 routing angular auth-guard angular5

我有一个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;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

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

export class userLoginService {
    constructor() {}
    IsloggedIn(): boolean {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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)
Run Code Online (Sandbox Code Playgroud)

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

小智 22

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

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

@Injectable()
export class AuthGuard implements CanActivate {
    ...
}
Run Code Online (Sandbox Code Playgroud)