Ошибка при использовании проверки подлинности CanActivate nullinjecterror - PullRequest
0 голосов
/ 28 марта 2020

Я пытаюсь внедрить защиту для некоторых страниц.

Здесь я хочу перенаправить на панель администратора

    if (user.is_activated) {
      this.isActivated = true;
      this.router.navigate(['/admin']);
    }

Моя проверка подлинности выглядит следующим образом

// src/app/auth/auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuardService implements CanActivate {
    constructor(public auth: AuthService, public router: Router) {}

    canActivate(): boolean {
        if (!this.auth.isLoggedIn()) {
            this.router.navigate(['login']);
            return false;
        }
        return true;
    }
}

и в моем app.routing.ts у меня есть следующее:

import { AuthGuardService } from './_services/auth.guard';
const routes: Routes = [
  {
    path: 'admin',
    component: AdminLayoutComponent,
    canActivate: [AuthGuardService],
    children: [
      {
        path: '',
        loadChildren: () => import('./layouts/admin-layout/admin-layout.module').then(m => m.AdminLayoutModule)
      }
    ]
  },
...
...
...

Я получаю следующую ошибку:

core.js:4002 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[AuthGuardService]: 
  StaticInjectorError(Platform: core)[AuthGuardService]: 
    NullInjectorError: No provider for AuthGuardService!
NullInjectorError: StaticInjectorError(AppModule)[AuthGuardService]: 
  StaticInjectorError(Platform: core)[AuthGuardService]: 
    NullInjectorError: No provider for AuthGuardService!
    at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:725)
    at resolveToken (core.js:11918)
    at tryResolveToken (core.js:11862)
    at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:11764)
    at resolveToken (core.js:11918)
    at tryResolveToken (core.js:11862)
    at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:11764)
    at resolveNgModuleDep (core.js:20234)
    at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:20905)
    at getToken (router.js:2855)
    at resolvePromise (zone.js:852)
    at resolvePromise (zone.js:809)
    at zone.js:913
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:26247)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)
    at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:502)
    at invokeTask (zone.js:1693)

1 Ответ

0 голосов
/ 28 марта 2020

Я решил это, настроив Injectable часть AuthGuardService

// src/app/auth/auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
    providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
    constructor(public auth: AuthService, public router: Router) {}

    canActivate(): boolean {
        if (!this.auth.isLoggedIn) {
            this.router.navigate(['login']);
            return false;
        }
        return true;
    }
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...