Issue Description
Angular runtime gives error-nullinjectorerror: no provider for httpclient!
ERROR NullInjectorError: R3InjectorError(AppModule)[AccountService -> HttpClient -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!
at NullInjector.get (http://localhost:4200/vendor.js:11077:27)
at R3Injector.get (http://localhost:4200/vendor.js:25117:33)
In Chrome or other browser,
Resolution
The issue is more due to not registering the required services i.e HttpClientModule in the root module ie. NgModule.
As per Angular Design and Architecture every service (internal or external service) is required to be registered with root NgModule as required.
This issue could exist in the Application and in the Unit Test project also. Please follow the below steps to resolve the issue.
Please register HttpClientModule in the root NgModule. File location app.module.ts
Add import statement as below,
import { HttpClientModule } from '@angular/common/http';
Also please update @NgModule decorator within the import section as below in the same file,
imports: [ BrowserModule, AppRoutingModule, HttpClientModule ],
Example:
Configure for Test project error- no provider for httpclient
While writing the Unit test for HttpClient dependent services you may find it is very useful to use HttpClientTestingModule.
This module is very helpful for testing especially Data services that make HTTP calls to the Servers. Please import the HttpClientTestingModule and the mocking controller, HttpTestingController, along with the other symbols your tests require.
Please add below import statement,
import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing';
Then please add the HttpClientTestingModule to the TestBed.
beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule ] });
Example:
Did I miss anything else in these resolution steps?
Did the above steps resolve your issue? Please sound off your comments below!
References:
- Angular – HTTP GET, PUT, POST and DELETE Request Examples
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to get a notification on freshly published best practices and guidelines for software design and development.
🐞 bug report
Affected Package
@angular/core
Is this a regression?
Yes, only happens with ivy. If I disable ivy, everything works as expected
"angularCompilerOptions": {
"enableIvy": false
}
Description
We are using ionic-native for our crossplatform apps. So we created some libraries to share code between different apps. If we use ionic-native (which has no providedIn root) we add the providers inside forRoot of a module in the library (1), build the library and add this module from our library in our AppModule (2). If we now using the service from the lib (3), the error occurs on start-up
We created an minimal repo where you can see the issue.
(1) https://github.com/paulstelzer/angular-ionic-issue/blob/master/projects/inno-core/src/lib/inno-core.module.ts
(2) https://github.com/paulstelzer/angular-ionic-issue/blob/master/src/app/app.module.ts
(3) https://github.com/paulstelzer/angular-ionic-issue/blob/master/src/app/app.component.ts
🔬 Minimal Reproduction
Github: https://github.com/paulstelzer/angular-ionic-issue
Nice to know: The «dist» folder is already comitted, so you do not need to build the lib. If you want just run npm run lib:build
,
npm i
ng serve
The app will show the error like mentioned below
🔥 Exception or Error
core.js:6185 ERROR NullInjectorError: R3InjectorError(AppModule)[PlatformService -> Device -> Device -> Device]:
NullInjectorError: No provider for Device!
at NullInjector.get (http://localhost:4200/vendor.js:36155:27)
at R3Injector.get (http://localhost:4200/vendor.js:49871:33)
at R3Injector.get (http://localhost:4200/vendor.js:49871:33)
at R3Injector.get (http://localhost:4200/vendor.js:49871:33)
at injectInjectorOnly (http://localhost:4200/vendor.js:36010:33)
at ɵɵinject (http://localhost:4200/vendor.js:36020:57)
at Object.PlatformService_Factory [as factory] (http://localhost:4200/main.js:103:356)
at R3Injector.hydrate (http://localhost:4200/vendor.js:50107:63)
at R3Injector.get (http://localhost:4200/vendor.js:49859:33)
at NgModuleRef$1.get (http://localhost:4200/vendor.js:67203:33)
🌍 Your Environment
Angular Version:
Angular CLI: 9.0.7
Node: 10.16.0
OS: win32 x64
Angular: 9.0.7
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: Yes
Package Version
------------------------------------------------------------
@angular-devkit/architect 0.900.7
@angular-devkit/build-angular 0.900.7
@angular-devkit/build-ng-packagr 0.900.7
@angular-devkit/build-optimizer 0.900.7
@angular-devkit/build-webpack 0.900.7
@angular-devkit/core 9.0.7
@angular-devkit/schematics 9.0.7
@ngtools/webpack 9.0.7
@schematics/angular 9.0.7
@schematics/update 0.900.7
ng-packagr 9.0.3
rxjs 6.5.4
typescript 3.7.5
webpack 4.41.2
Anything else relevant?
We building the library with ng-packagr! This can also be a bug of ionic-native!
Post
- An Article
- A Blog
- A Video
- An EBook
- An Interview Question
- 2.2k
- 5
- 4.9k
I’m getting the below error after migratring my angular5 project to angular8
ERROR NullInjectorError: R3InjectorError(AppModule)[Renderer]:
StaticInjectorError(AppModule)[Renderer]:
StaticInjectorError(Platform: core)[Renderer]:
NullInjectorError: No provider for Renderer!
at NullInjector.get (http://purplle.local.com/static/hello-ivy/dist/vendor-es2015.js:32721:27)
at resolveToken (http://purplle.local.com/static/hello-ivy/dist/vendor-es2015.js:33048:24)
at tryResolveToken (http://purplle.local.com/static/hello-ivy/dist/vendor-es2015.js:32974:16)
at StaticInjector.get (http://purplle.local.com/static/hello-ivy/dist/vendor-es2015.js:32837:20)
at resolveToken (http://purplle.local.com/static/hello-ivy/dist/vendor-es2015.js:33048:24)
at tryResolveToken (http://purplle.local.com/static/hello-ivy/dist/vendor-es2015.js:32974:16)
at StaticInjector.get (http://purplle.local.com/static/hello-ivy/dist/vendor-es2015.js:32837:20)
at R3Injector.get (http://purplle.local.com/static/hello-ivy/dist/vendor-es2015.js:50047:33)
at NgModuleRef$1.get (http://purplle.local.com/static/hello-ivy/dist/vendor-es2015.js:58502:33)
at Object.get (http://purplle.local.com/static/hello-ivy/dist/vendor-es2015.js:56384:35)
Answers (2)
I am using Angular 9.
I am getting the following error:
No provider for FormBuilder
It has been reported in many cases, and the general solution appears to be to add the FormsModule
to the app.module.ts
file.
e.g.
import { FormsModule } from '@angular/forms'; imports: [ FormsModule
I have tried this, but am still getting the error.
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[FormBuilder -> FormBuilder -> FormBuilder]: NullInjectorError: No provider for FormBuilder! NullInjectorError: R3InjectorError(AppModule)[FormBuilder -> FormBuilder -> FormBuilder]: NullInjectorError: No provider for FormBuilder!
Question
Am I maybe doing something that’s changed in Angular 9? What do I need to do to fix this?
My code:
login.component.ts
import { Component, OnInit } from '@angular/core'; import {Router} from '@angular/router'; import { FormGroup, FormBuilder } from '@angular/forms'; import { AuthService } from '../../services/auth.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm: FormGroup; constructor(private authService: AuthService, private formBuilder: FormBuilder, private router: Router) { } ngOnInit(): void { this.loginForm = this.formBuilder.group({ username: [''], password: [''] }); } get f() { return this.loginForm.controls; } login() { this.authService.login( { username: this.f.username.value, password: this.f.password.value } ) .subscribe(success => { if (success) { this.router.navigate(['/secret-random-number']); } }); } }
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './auth/containers/login/login.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FlexLayoutModule } from '@angular/flex-layout'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatToolbarModule } from '@angular/material/toolbar'; import { FormsModule } from '@angular/forms'; import { ApprovalListComponent } from './approval-list/component/approval-list.component'; import { MatTableModule } from '@angular/material/table'; import { MatPaginatorModule } from '@angular/material/paginator'; import { MatSortModule } from '@angular/material/sort'; import { MatTableExporterModule } from 'mat-table-exporter'; @NgModule({ declarations: [ AppComponent, LoginComponent, ApprovalListComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, BrowserAnimationsModule, FlexLayoutModule, MatFormFieldModule, MatInputModule, MatButtonModule, MatCardModule, MatToolbarModule, FormsModule, MatTableModule, MatPaginatorModule, MatSortModule, MatTableExporterModule ], providers: [LoginComponent], bootstrap: [AppComponent] }) export class AppModule { }
Advertisement
Answer
form builder is ReactiveFormsModule
import { ReactiveFormsModule } from '@angular/forms'; imports: [ ReactiveFormsModule
you’ll also need this module to use formGroup
and formControl
directives.
4 People found this is helpful
Issue
I have an error message:
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(MarketModule)
[IndiceService -> IndiceService -> IndiceService -> IndiceService -> IndiceService]:
NullInjectorError: No provider for IndiceService! NullInjectorError:
R3InjectorError(MarketModule)[IndiceService -> IndiceService
Error in the console
the indice.service.ts file is presented like this:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { IndiceResponse } from './folder/indice.response';
@Injectable()
export class IndiceService {
private readonly api: string = environment.api;
constructor(private http: HttpClient) { }
getIndices(): Observable<IndiceResponse> {
return this.http.post<IndiceResponse>(this.api + `/AZEMONDL`, {
FILTRE: {
LASTACTIF_CODE: "1W"
}
});
}
}
indice.component.ts file
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Subject, takeUntil } from 'rxjs';
import { CreateDateTimePipe } from 'src/app/shared/pipes/create-date-time.pipe';
import { Indice } from './folder/indice';
import { IndiceService } from './indice.service';
@Component({
selector: 'app-indice',
templateUrl: './indice.component.html',
styleUrls: ['./indice.component.css']
})
export class IndiceComponent implements OnInit, OnDestroy {
private unsubscribe$ = new Subject<void>();
indices: Indice[] = [];
selectedIndex: string = '';
indiceDatas: any;
constructor(
private service: IndiceService,
private router: Router,
private createDateTimePipe: CreateDateTimePipe) { }
ngOnInit(): void {
this.getIndices();
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
I also have a strange message for the Router
:
Property 'router' is declared but its value is never read.
Error Visual Studio Code
indice.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { PipesModule } from 'src/app/shared/pipes/pipes.module';
@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule,
PipesModule,
]
})
export class IndiceModule { }
I don’t know where these problems come from? Thank you for your help.
Solution
The issue you are getting is because Angular doesn’t know about the IndiceService
yet.
You either have to define it at the root level:
@Injectable({
providedIn:'root'
})
export class IndiceService {...}
Or in your IndiceModule
inside providers
array:
@NgModule({
...
providers:[IndiceService]; //Add it to the import also above
})
export class IndiceModule { }
The difference between the 2 is with ‘root’ level service, its single instance will be created & shared throughout the application. While adding it in the providers
array, its instance will be shared within this module only.
Property ‘router’ is declared but its value is never read.
This error is generated by the Typescript compiler because you have injected Router
in your IndiceComponent
, but it is not used. So, it warns you to remove it if it is not used.
Answered By — Pankaj Sati