代码之家  ›  专栏  ›  技术社区  ›  Laiso

无法解析AuthGuard的所有参数

  •  6
  • Laiso  · 技术社区  · 7 年前

    我有这个 AuthGuard :

    export class AuthGuard implements CanActivate {
    
      constructor (private router: Router) {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        if (localStorage.getItem('token')) {
          return true;
        }
    
        this.router.navigate(['/login']);
        return false;
      }
    }
    

    AppModule :

    @NgModule({
      declarations: [/*...*/],
      imports: [NotificationRoutingModule],
      providers: [AuthService, AuthGuard],
      bootstrap: [AppComponent]
    })
    export class AppModule {
    }
    

    我试着在我的路由模块中使用这个防护,如下所示:

    const routes = [
      {
        path: 'notification',
        component: NotificationRootComponent
        children: [
          {path: '', redirectTo: 'list', pathMatch: 'full'},
          {path: 'list', component: NotificationListComponent, canActivate: [AuthGuard]},
          {path: ':id', component: NotificationDetailComponent, canActivate: [AuthGuard]}
        ]
      }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule],
      declarations: []
    })
    export class NotificationRoutingModule {
    }
    

    我得到了这个错误:

    enter image description here

    我错过什么了吗?这个错误的来源在哪里?

    编辑: 我使用的是Angular 4.4.6

    当我使用基本路由保护并更新路由配置时,它工作正常:

    @NgModule({
      declarations: [],
      imports: [],
      providers: [
        {
          provide: 'CannotBeActivated',
          useValue: () => {
            return false;
          }
        }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {
    }
    
    
    const routes = [
      {
        path: 'notification',
        component: NotificationRootComponent,
        children: [
          {path: '', redirectTo: 'list', pathMatch: 'full'},
          {path: 'list', component: NotificationListComponent, canActivate: ['CannotBeActivated']},
          {path: ':id', component: NotificationDetailComponent, canActivate: ['CannotBeActivated']}
        ]
      }
    ];
    

    **我的tsconfig。json:**

    {
      "compileOnSave": false,
      "compilerOptions": {
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es5",
        "typeRoots": [
          "node_modules/@types"
        ],
        "lib": [
          "es2017",
          "dom"
        ]
      }
    }
    
    1 回复  |  直到 6 年前
        1
  •  13
  •   Faly    7 年前

    您刚刚错过了将@Injectable()放在AuthGuard服务之前