正如您在上传的图像中所看到的,我已经导入了使用 httpClient 时应有的所有内容,但是当转到我使用守卫的路线时,我收到此错误。
ERROR NullInjectorError: NullInjectorError: No provider for _HttpClient!
at NullInjector.get (core.mjs:4674:27)
at R3Injector.get (core.mjs:5117:33)
at R3Injector.get (core.mjs:5117:33)
at injectInjectorOnly (core.mjs:3831:40)
at Module.ɵɵinject (core.mjs:3837:42)
at Object.AuthService_Factory [as factory] (auth.service.ts:8:25)
at core.mjs:5239:43
at runInInjectorProfilerContext (core.mjs:3644:9)
at R3Injector.hydrate (core.mjs:5238:17)
at R3Injector.get (core.mjs:5106:33)
我的守护者:
import { CanMatchFn } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { inject } from '@angular/core';
export const authGuard: CanMatchFn = (route, segments) => {
const authService = inject(AuthService);
if(authService.auth.id){
return true;
}
return false;
};
我使用的路线
{
path: 'heroes',
loadChildren: () => import('./heroes/heroes.module').then(m => m.HeroesModule),
canMatch: [authGuard]
},
如果我删除 canMatch: [authGuard],那么工作正常,应该是这样,因为我之前一直在我的项目中使用 httpClient 并且一切正常
您遇到的错误是因为 AuthService 在没有提供程序的情况下注入 HttpClient。我猜你的 AuthService 被用作单例,所以你可以只在 app.module.ts 中导入 HttpClientModule,或者如果你在 Angular 17+ 中工作,你可以通过 ProvideHttpClient() 在 appConfiguration 中提供它。