在 canActivate 类中使用 HttpClient 时出错 | [错误] NullInjectorError:没有 _HttpClient 的提供者

问题描述 投票:0回答:2

当我想在 CanActivate 类中使用 HttpClient 时遇到一些麻烦。 我想做一些 POST 请求,以便在 Django API 中找到我的令牌。 例子胜于雄辩:

auth.guard.ts

import { Injectable, NgModule } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { HttpClient, HttpClientModule } from "@angular/common/http";


@Injectable({
    providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
    constructor(private router: Router,
        private http: HttpClient,
    ) { }

    async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {

        const expectedRole: string[] = route.data['expectedRole'];

        if (localStorage.getItem('token') == null) {
            this.router.navigate(['http://localhost:3000']);
            return false;
        }
        this.http.post<any>('api/verify-token/', {
            token: localStorage.getItem('jwt')
        }).subscribe((data) => {
            if (!expectedRole.includes(data.role)) {
                this.router.navigate(['http://localhost:3000']);
              }
              return true;
        }, err => {
            this.router.navigate(['http://localhost:3000']);
            return false;
        }
        )

        return false;
    }
}

app.route.ts

import { Routes, RouterModule } from '@angular/router';
import { AddUserComponent } from './add-user/add-user.component';
import { NgModule } from '@angular/core';
import { AuthGuardService } from './auth.guard';

export const routes: Routes = [
    // routes...
    { path: 'add-user', component: AddUserComponent, canActivate: [AuthGuardService], data: { expectedRole: ['Administrateur'] } },
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule], 
    providers: []
})

export class AppRouteModule { }

当我尝试访问我的路线时,出现此错误:

ERROR Error [NullInjectorError]: R3InjectorError(Environment Injector)[_AuthGuardService -> _HttpClient -> _HttpClient]: 
  NullInjectorError: No provider for _HttpClient!
    at NullInjector.get 
    at R3Injector.get 
    at R3Injector.get 
    at injectInjectorOnly 
    at Module.ɵɵinject 
    at Object.AuthGuardService_Factory
    at eval 
    at runInInjectorProfilerContext 
    at R3Injector.hydrate 
    at R3Injector.get  {
  ngTempTokenPath: null,
  ngTokenPath: [ '_AuthGuardService', '_HttpClient', '_HttpClient' ]

你能解释一下我错在哪里吗

angular angular-ui-router canactivate
2个回答
0
投票

您需要将

HttpClientModule
导入到
app.module.ts
或您正在使用的根模块

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [...],
  imports: [HttpClientModule],
  providers: [...]
})
export class AppModule {}

0
投票

当使用

root
中提供的服务时,您可以使用
inject()
添加依赖项,如下所示!

import { Injectable, NgModule, inject } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { HttpClient, HttpClientModule } from "@angular/common/http";


@Injectable({
    providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
    private router = inject(Router));
    private http= inject(HttpClient));
    constructor() { }

    async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {

        const expectedRole: string[] = route.data['expectedRole'];

        if (localStorage.getItem('token') == null) {
            this.router.navigate(['http://localhost:3000']);
            return false;
        }
        this.http.post<any>('api/verify-token/', {
            token: localStorage.getItem('jwt')
        }).subscribe((data) => {
            if (!expectedRole.includes(data.role)) {
                this.router.navigate(['http://localhost:3000']);
              }
              return true;
        }, err => {
            this.router.navigate(['http://localhost:3000']);
            return false;
        }
        )

        return false;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.