Reputation: 7709
After upgrading from angular 4.4 to 5.0 and after updating all HttpModule and Http to HttpClientModule I started to get this error.
I also added HttpModule again to be sure it's not due to some dependency but it doesn't resolve the issue
In app.module, I have all correctly set
import { HttpModule } from '@angular/http';
import { HttpClientModule, HttpClient } from '@angular/common/http';
.
.
.
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
HttpModule,
BrowserAnimationsModule,
FormsModule,
AppRoutingModule,
.
.
.
I don't know from where this error is coming, or I have no clue how to get inner of it. I also have a warning (put it below too) maybe its related.
Error: StaticInjectorError[HttpClient]:
StaticInjectorError[HttpClient]:
NullInjectorError: No provider for HttpClient!
at _NullInjector.get (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5665)
at resolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5953)
at tryResolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5895)
at StaticInjector.get (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5766)
at resolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5953)
at tryResolveToken (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5895)
at StaticInjector.get (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:5766)
at resolveNgModuleDep (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:15328)
at _createClass (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:15373)
at _createProviderInstance$1 (vendor.js?v=mekBM8IVBK72-MIZOVSTJizGi_TD_xK3uhPOCRlEHwg:15339)
Warning Message:
./node_modules/@angular/Common/esm5/http.js
There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
* D:\XXX\node_modules\@angular\Common\esm5\http.js
Used by 21 module(s), i. e.
D:\XXX\node_modules\awesome-typescript-loader\dist\entry.js?silent=true!D:\XXX\node_modules\angular2-template-loader\index.js!D:\XXX\ClientApp\app\services\notification-endpoint.service.ts
* D:\XXX\node_modules\@angular\common\esm5\http.js
Used by 1 module(s), i. e.
D:\XXX\node_modules\awesome-typescript-loader\dist\entry.js?silent=true!D:\XXX\node_modules\angular2-template-loader\index.js!D:\XXX\ClientApp\app\app.module.ts
@ ./node_modules/@angular/Common/esm5/http.js
@ ./ClientApp/app/services/notification-endpoint.service.ts
@ ./ClientApp/app/app.module.ts
@ ./ClientApp/boot.browser.ts
@ multi event-source-polyfill webpack-hot-middleware/client?path=__webpack_hmr&dynamicPublicPath=true ./ClientApp/boot.browser.ts
StaticInjectorError[HttpClient]: StaticInjectorError[HttpClient]: NullInjectorError: No provider for HttpClient!
Angular version: 5.0.0 and 5.0.1 (also 5.1 beta)
Browser:
- all
For Tooling issues:
- Node version: 8.5.0
- Platform: windows
{
"name": "X",
"version": "1.0.0",
"description": "X",
"author": {
"name": "X X",
"email": "XX",
"url": "X"
},
"homepage": "X",
"dependencies": {
"@angular/animations": "^5.1.0-beta.0",
"@angular/common": "^5.1.0-beta.0",
"@angular/compiler": "^5.1.0-beta.0",
"@angular/compiler-cli": "^5.1.0-beta.0",
"@angular/core": "^5.1.0-beta.0",
"@angular/forms": "^5.1.0-beta.0",
"@angular/http": "^5.1.0-beta.0",
"@angular/platform-browser": "^5.1.0-beta.0",
"@angular/platform-browser-dynamic": "^5.1.0-beta.0",
"@angular/platform-server": "^5.1.0-beta.0",
"@angular/router": "^5.1.0-beta.0",
"@ngtools/webpack": "^1.8.0",
"@ngx-translate/core": "^8.0.0",
"@ngx-translate/http-loader": "^2.0.0",
"@swimlane/ngx-datatable": "^11.0.3",
"@types/jquery": "^3.2.16",
"@types/webpack-env": "^1.13.2",
"angular2-template-loader": "^0.6.2",
"aspnet-webpack": "^2.0.1",
"awesome-typescript-loader": "^3.3.0",
"bootstrap": "^3.3.7",
"bootstrap-datepicker": "^1.7.1",
"bootstrap-select": "^1.12.4",
"bootstrap-toggle": "^2.2.2",
"bootstrap-vertical-tabs": "^1.2.2",
"chart.js": "^2.7.1",
"core-js": "^2.5.1",
"css": "^2.2.1",
"css-loader": "^0.28.7",
"event-source-polyfill": "^0.0.11",
"expose-loader": "^0.7.3",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.5",
"font-awesome": "^4.7.0",
"html-loader": "^0.5.1",
"jquery": "^3.2.1",
"json-loader": "^0.5.7",
"ng2-charts": "^1.6.0",
"ng2-toasty": "^4.0.3",
"ngx-bootstrap": "^2.0.0-beta.8",
"node-sass": "^4.6.0",
"popper.js": "^1.12.6",
"raw-loader": "^0.5.1",
"rxjs": "^5.5.2",
"sass-loader": "^6.0.6",
"style-loader": "^0.19.0",
"to-string-loader": "^1.1.5",
"typescript": "^2.6.1",
"url-loader": "^0.6.2",
"web-animations-js": "^2.3.1",
"webpack": "^3.8.1",
"webpack-hot-middleware": "^2.20.0",
"webpack-merge": "^4.1.1",
"zone.js": "^0.8.18"
},
"devDependencies": {
"@types/chai": "^4.0.4",
"@types/jasmine": "^2.6.3",
"chai": "^4.1.2",
"jasmine-core": "^2.8.0",
"karma": "^1.7.1",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"karma-webpack": "^2.0.5"
},
"scripts": {
"dev-build": "node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js",
"test": "karma start ClientApp/test/karma.conf.js"
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
context: __dirname,
resolve: { extensions: ['.js', '.ts'] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
{ test: /\.scss$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize', 'sass-loader'] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot.browser.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.module#AppModule')
})
])
});
return [clientBundleConfig];
};
webpack.config.vendor.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
'@angular/animations',
'@angular/common',
'@angular/compiler',
'@angular/core',
'@angular/forms',
'@angular/http',
'@angular/platform-browser',
'@angular/platform-browser-dynamic',
'@angular/router',
'zone.js',
];
const nonTreeShakableModules = [
'bootstrap',
'core-js/client/shim',
'web-animations-js',
'event-source-polyfill',
'jquery',
'@swimlane/ngx-datatable/release/assets/icons.css',
'ng2-toasty',
'ng2-toasty/bundles/style-bootstrap.css',
'ng2-charts',
'ngx-bootstrap/modal',
'ngx-bootstrap/tooltip',
'ngx-bootstrap/popover',
'ngx-bootstrap/dropdown',
'ngx-bootstrap/carousel',
'bootstrap-vertical-tabs/bootstrap.vertical-tabs.css',
'bootstrap-toggle/css/bootstrap-toggle.css',
'bootstrap-toggle/js/bootstrap-toggle.js',
'bootstrap-select/dist/css/bootstrap-select.css',
'bootstrap-select/dist/js/bootstrap-select.js',
'bootstrap-datepicker/dist/css/bootstrap-datepicker3.css',
'font-awesome/css/font-awesome.css'
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);
module.exports = (env) => {
const extractCSS = new ExtractTextPlugin('vendor.css');
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
resolve: { extensions: ['.js'] },
module: {
rules: [
{ test: /\.(gif|png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
output: {
publicPath: 'dist/',
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.ContextReplacementPlugin(/\@angular\b.*\b(bundles|linker)/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/11580
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, path.join(__dirname, './ClientApp')), // Workaround for https://github.com/angular/angular/issues/14898
new webpack.IgnorePlugin(/^vertx$/) // Workaround for https://github.com/stefanpenner/es6-promise/issues/100
]
};
const clientBundleConfig = merge(sharedConfig, {
entry: {
// To keep development builds fast, include all vendor dependencies in the vendor bundle.
// But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
vendor: isDevBuild ? allModules : nonTreeShakableModules
},
output: { path: path.join(__dirname, 'wwwroot', 'dist') },
module: {
rules: [
{ test: /\.css(\?|$)/, use: extractCSS.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
]
},
plugins: [
extractCSS,
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin()
])
});
return [clientBundleConfig];
}
Upvotes: 762
Views: 1057773
Reputation: 99
This mean your Angular application requires Http provider dependency which is not defined in your application configuration file.
to solve it, you need to add provideHttpClient to your configuration array
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()]
};
Upvotes: 3
Reputation: 1677
With the recent changes in angular (Angular 17) there is no app.module file. So with the new structure you will have to update it in app.config file and add
provideHttpClient()
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http'
import { provideRouter, withHashLocation } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withHashLocation()),
provideHttpClient()
]
};
or if you want to add auth interceptor then you can do it like
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http'
import { provideRouter, withHashLocation } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withHashLocation()),
provideHttpClient(withInterceptors([authenticationInterceptor]))
]
};
interceptor can be declared like
import { HttpHandlerFn, HttpInterceptorFn, HttpRequest } from "@angular/common/http";
export const authenticationInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next:
HttpHandlerFn) => {
const modifiedReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${sessionStorage.getItem('token')}`),
});
return next(modifiedReq);
};
Upvotes: 76
Reputation: 4627
If using Angular 18+, already existing provider function provideHttpClient() is now used and HttpClientModule is now deprecated. So, use this function to provide http ability to application module.
@NgModule({
imports: [
BrowserModule,
// Remove the module if any
],
declarations: [
AppComponent,
...
],
providers: [provideHttpClient()] // use provider function here
bootstrap: [ AppComponent ]
})
export class AppModule {}
Upvotes: 1
Reputation: 186
In Angular 17 - NullInjectorError: No provider for _HttpClient! Go to your app.config.ts Inside the providers array add:
provideHttpClient()
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideClientHydration(),
provideAnimationsAsync(),
provideHttpClient(),
],
};
This fixed my error
Upvotes: 11
Reputation: 73
I had the same problem for a long time and tried many things and some answers from stackOverflow
, but for me, there was a missing part of making your project work especially for the new angular version.
first: add HttpClientModule
to the root app in the file app.module.ts
in the import[]
array.
second: add the services to the file app.module.ts
in the providers[]
, or inject this service to root application from the service file by using this code inside the service file.
@Injectable({
providedIn: 'root'
})
The last and most important part was for me is to add importProvidersFrom(HttpClientModule)
to the providers: []
array in the app.config.ts
file and import the suitable libraries.
import { ApplicationConfig } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { importProvidersFrom } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [
importProvidersFrom(HttpClientModule),
]
};
Upvotes: 6
Reputation: 17432
Fixed by adding HttpClientModule
provider in imports
section
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
]
})
This we need to add in src -> app -> app.module.ts
file.
Upvotes: 11
Reputation: 6196
The issue is more due to not registering the required services i.e HttpClientModule
in the root module ie. NgModule
.
You are missing HttpClientModule
since you are receiving an error for HttpClient
You should import it in the app.module.ts
file as follows,
import { HttpClientModule } from '@angular/common/http';
and mention it in the NgModule
Decorator like this -
@NgModule({
...
imports:[ HttpClientModule ]
...
})
Hopefully, it may work. See the below image to getting more idea.
Upvotes: 22
Reputation: 551
Upvotes: -1
Reputation: 119
Added
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [...],
imports: [
...
HttpClientModule,
],
providers: [...],
bootstrap: [...],
})
export class AppModule {}
to root module of my-app solved this problem
Upvotes: 1
Reputation: 4096
My particular issue was that, while I was including HttpClientModule
correctly in my App Module, where I was injecting a HttpClient
had imported the "wrong" HttpClient, specifically the HttpClient from a signalr
package.
import { HttpClient } from '@aspnet/signalr';
Because I didn't pay attention when the autocomplete was happening,
I'm have to assume some others have hit a similar issue as well, not that they just haven't imported the HttpClientModule in their App Module.
Upvotes: 3
Reputation: 331
step 1: import the HttpClientModule
in app.module.ts:
import { HttpClientModule} from '@angular/common/http';
step 2: inside the module imports add HttpClientModule
:
@NgModule({
declarations: [
...
],
imports: [
HttpClientModule
],
providers: [
....
],
bootstrap: [AppComponent]
})
Upvotes: 32
Reputation: 1018
Under app.module.ts -> import section, you need to add HttpClientModule. Below is the sample
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule, // This is where you need to add
FormsModule,
...
Upvotes: 10
Reputation: 4557
Just Add HttpClientModule
in 'imports' array of app.module.ts
file.
...
import {HttpClientModule} from '@angular/common/http'; // add this line
@NgModule({
declarations: [
AppComponent,
HeaderComponent
],
imports: [
BrowserModule,
HttpClientModule, //add this line
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
and then you can use HttpClient
in your project through constructor injection
import {HttpClient} from '@angular/common/http';
export class Services{
constructor(private http: HttpClient) {}
Upvotes: 47
Reputation: 363
Go to app.module.ts
import import { HttpClientModule } from '@angular/common/http';
AND
Add HttpClientModule
under imports
should look like this
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule]
Upvotes: 22
Reputation: 186
In my case, I was using a service in a sub module (NOT the root AppModule), and the HttpClientModule was imported only in the module.
So I have to modify the default scope of the service, by changing 'providedIn' to 'any' in the @Injectable decorator.
By default, if you using angular-cli to generate the service, the 'providedIn' was set to 'root'.
Hope this helps.
Upvotes: 4
Reputation: 385
I got this error after injecting a Service which used HTTPClient into a class. The class was again used in the service, so it created a circular dependency. I could compile the app with warnings, but in browser console the error occurred
"No provider for HttpClient! (MyService -> HttpClient)"
and it broke the app.
This works:
import { HttpClient, HttpClientModule, HttpHeaders } from '@angular/common/http';
import { MyClass } from "../classes/my.class";
@Injectable()
export class MyService {
constructor(
private http: HttpClient
){
// do something with myClass Instances
}
}
.
.
.
export class MenuItem {
constructor(
){}
}
This breaks the app
import { HttpClient, HttpClientModule, HttpHeaders } from '@angular/common/http';
import { MyClass } from "../classes/my.class";
@Injectable()
export class MyService {
constructor(
private http: HttpClient
){
// do something with myClass Instances
}
}
.
.
.
import { MyService } from '../services/my.service';
export class MyClass {
constructor(
let injector = ReflectiveInjector.resolveAndCreate([MyService]);
this.myService = injector.get(MyService);
){}
}
After injecting MyService in MyClass I got the circular dependency warning. CLI compiled anyway with this warning but the app did not work anymore and the error was given in browser console. So in my case it didn't had to do anything with @NgModule but with circular dependencies. I recommend to solve the case sensitive naming warnings if your problem still exist.
Upvotes: 12
Reputation: 13577
To resolve this problem HttpClient
is Angular's mechanism for communicating with a remote server over HTTP.
To make HttpClient
available everywhere in the app,
open the root AppModule
,
import the HttpClientModule
from @angular/common/http
,
import { HttpClientModule } from '@angular/common/http';
add it to the @NgModule.imports
array.
imports:[HttpClientModule, ]
Upvotes: 1322
Reputation: 83
In my case I found once I rebuild the app it worked.
I had imported the HttpClientModule
as specified in the previous posts but I was still getting the error. I stopped the server, rebuilt the app (ng serve
) and it worked.
Upvotes: 4
Reputation: 13194
In my case, the error occured when using a service from an angular module located in an npm package, where the service requires injection of HttpClient
. When installing the npm package, a duplicate node_modules
directory was created inside the package directory due to version conflict handling of npm (engi-sdk-client
is the module containing the service):
Obviously, the dependency to HttpClient
is not resolved correctly, as the locations of HttpClientModule
injected into the service (lives in the duplicate node_modules
directory) and the one injected in app.module
(the correct node_modules
) don't match.
I've also had this error in other setups containing a duplicate node_modules
directory due to a wrong npm install
call.
This defective setup also leads to the described runtime exception No provider for HttpClient!
.
TL;DR; Check for duplicate
node_modules
directories, if none of the other solutions work!
Upvotes: 2
Reputation: 240
I was facing the same problem, then in my app.module.ts I updated the file this way,
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
and in the same file (app.module.ts) in my @NgModule imports[]array I wrote this way,
HttpModule,
HttpClientModule
Upvotes: 14
Reputation: 827
I had similar problem. For me the fix was to import HttpModule before HttpClient Module:
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
.
.
.
imports: [
BrowserModule,
HttpModule,
HttpClientModule
],
Upvotes: 7
Reputation: 3347
I was facing the same issue, the funny thing was I had two projects opened on simultaneously, I have changed the wrong app.modules.ts files.
First, check that.
After that change add the following code to the app.module.ts file
import { HttpClientModule } from '@angular/common/http';
After that add the following to the imports array in the app.module.ts file
imports: [
HttpClientModule,....
],
Now you should be ok!
Upvotes: 18
Reputation: 3502
Add HttpModule
and HttpClientModule
in both imports and providers in app.module.ts solved the issue.
imports -> import {HttpModule} from "@angular/http";
import {HttpClientModule} from "@angular/common/http";
Upvotes: 7
Reputation: 101
I found slimier problem. Please import the HttpClientModule in your app.module.ts file as follow:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Upvotes: 10
Reputation: 470
I was also facing similar issue by doing below changes, it worked for me
In app.modules.ts
import {HttpClientModule} from '@angular/common/http'
and in corresponding service class
import { HttpClient } from '@angular/common/http'
constructor should look like as below
constructor(private http: HttpClient, private xyz: xyzService) {}
In test file
import { HttpClientTestingModule } from '@angular/common/http/testing'
beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
}));
Upvotes: 31
Reputation: 743
I had same issue. After browsing and struggling with issue found the below solution
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
imports: [
HttpModule,
HttpClientModule
]
Import HttpModule
and HttpClientModule
in app.module.ts and add into the imports like mentioned above.
Upvotes: 36
Reputation: 881
You are getting error for HttpClient so, you are missing HttpClientModule for that.
You should import it in app.module.ts file like this -
import { HttpClientModule } from '@angular/common/http';
and mention it in the NgModule Decorator like this -
@NgModule({
...
imports:[ HttpClientModule ]
...
})
If this even doesn't work try clearing cookies of the browser and try restarting your server. Hopefully it may work, I was getting the same error.
Upvotes: 69
Reputation: 2497
You have not provided providers in your module:
<strike>import { HttpModule } from '@angular/http';</strike>
import { HttpClientModule, HttpClient } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule,
FormsModule,
AppRoutingModule
],
providers: [ HttpClientModule, ... ]
// ...
})
export class MyModule { /* ... */ }
You will need to add the HttpClientTestingModule
to the TestBed configuration when running ng test
and getting the "No provider for HttpClient" error:
// Http testing module and mocking controller
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
// Other imports
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
describe('HttpClient testing', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
// Inject the http service and test controller for each test
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
});
it('works', () => {
});
});
Upvotes: 235
Reputation: 634
Just import the HttpModule
and the HttpClientModule
only:
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
No need for the HttpClient
.
Upvotes: 6
Reputation: 1826
In angular github page, this problem was discussed and found solution. https://github.com/angular/angular/issues/20355
Upvotes: 5