Frontend/Angular
앵귤러 NullInjectorError: No provider for _HttpClient! 오류 해결
컴슈터
2024. 3. 29. 14:13
문제 발생
앵귤러에서 HTTP 통신을 하기 위해 HttpClient
를 이용하려고 한다. 서비스의 constructor에서 HttpClient를 가져다썼더니 NullInjectorError 에러가 발생했다.
import { HttpClient } from '@angular/common/http';
@Injectable()
export class UserService {
constructor(public httpClient: HttpClient) { } // 여기서 문제 발생
}
NullInjectorError
에러의 내용은 HttpClient에 대한 provider가 없다는 의미다.
ERROR NullInjectorError: R3InjectorError(_AppModule)[_UserService -> _HttpClient -> _HttpClient]:
NullInjectorError: No provider for _HttpClient!
at NullInjector.get (core.mjs:1654:27)
at R3Injector.get (core.mjs:3093:33)
at R3Injector.get (core.mjs:3093:33)
at injectInjectorOnly (core.mjs:1100:40)
at Module.ɵɵinject (core.mjs:1106:42)
at Object.UserService_Factory [as factory] (user.service.ts:8:25)
at core.mjs:3219:47
at runInInjectorProfilerContext (core.mjs:866:9)
at R3Injector.hydrate (core.mjs:3218:21)
at R3Injector.get (core.mjs:3082:33)
해결 방법
HttpClient 모듈을 앱의 모든 곳에서 사용할 수 있게 하려면, AppModule에서 해당 모듈을 추가하기만 하면 된다. 즉 아래처럼 HttpClientModule을 import한 뒤, @NgModule 내의 imports에서 모듈을 추가한다.
[app.module.ts]
import { HttpClientModule } from '@angular/common/http'; // 추가
@NgModule({
// 생략...
imports: [
HttpClientModule // 추가
],
})
export class AppModule { }