749

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

Current behavior

StaticInjectorError[HttpClient]: StaticInjectorError[HttpClient]: NullInjectorError: No provider for HttpClient!

Environment

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];
}
13
  • are you using angular2-jwt? Commented Nov 11, 2017 at 10:40
  • stackoverflow.com/a/45129865/7018464 Commented Nov 11, 2017 at 11:03
  • is this an angular-cli project? could you please add your package.json Commented Nov 11, 2017 at 15:08
  • 1
    No, its a .core 2.0 project and it was working till angular 5 and httpclientmodule upgrade. And below link is also same with above answer but it doesnt helps because httpclient is already in constructors where its used. Commented Nov 11, 2017 at 15:16
  • 1
    No its not a duplicate they are different and its answer is already correct at my side and same problem happens even i have a test file and without a test file Commented Nov 13, 2017 at 13:59

30 Answers 30

1314

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,

  1. open the root AppModule,

  2. import the HttpClientModule from @angular/common/http,

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

  3. add it to the @NgModule.imports array.

    imports:[HttpClientModule, ]

7
  • This fixed it for me. I had put mine in the declarations by accident.
    – catch22
    Commented Mar 7, 2019 at 23:02
  • 4
    Import it only in the app.module, and nowhere else, not in sub modules Commented Dec 6, 2019 at 18:14
  • 4
    Too bad that the OP has not taken a second to accept this as the answer... Commented Dec 19, 2019 at 5:45
  • 1
    I am happy to announce this solution is covered by Assistant medium.com/@tomaszs2/… Commented Jul 26, 2020 at 8:55
  • 1
    I do this but this error stills, then I added HttpClientModule in te providers arrary in app.module.ts, then save and run fine then I delete HttpClientModule of providers arrays and run fine Commented Feb 6 at 21:59
231

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 { /* ... */ }

Using HttpClient in Tests

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', () => {
  });
});
10
  • 3
    no, this isnt documented that httpclientmodule should be added to providers list. But anyways, i tried your answer too to be sure but as expected the same error continues after adding it to providers list. Commented Nov 13, 2017 at 13:51
  • 18
    I guess "HttpClientModule" should be added to imports, not providers Commented Nov 23, 2017 at 6:06
  • 35
    I had to add imports: [HttpClientTestingModule] to my TestBed.configureTestingModule to get rid of this error in tests. Commented Dec 28, 2017 at 12:50
  • 1
    @YaroslavStavnichiy comment was the answer to my problem with this in Jasmine.
    – user796446
    Commented Dec 28, 2017 at 18:28
  • 10
    import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
    – NitinSingh
    Commented Feb 1, 2018 at 7:16
68

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.

1
  • Adding HttpClientModule to imports solved the issue, because its value was not used, Thanks @Vivek kushwaha
    – vidur punj
    Commented Mar 20, 2019 at 9:42
47

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) {}
1
  • 1
    Have spent a while scratching my head trying to figure out what went wrong. This solved it. Thank you. Commented May 4, 2022 at 17:54
44

With the recent changes in angular there is no app.module file. So with the new structure you will have to upate 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);
};
4
  • 2
    This worked for me with Angular 17. provideHttpClient is imported via import { provideHttpClient } from '@angular/common/http'; Commented Dec 30, 2023 at 20:28
  • it is working for me also in Angular 17
    – Igor Zinin
    Commented Jan 16 at 9:57
  • Worked for me with Angular 17. Thank you. Commented Feb 6 at 18:39
  • @YogeshJog please add the resource docs Commented Mar 31 at 12:02
36

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.

2
  • 7
    using the HttpModule (deprecated) and the HttpClientModule (replaces HttpModule) makes no sense
    – themenace
    Commented Nov 20, 2018 at 12:46
  • 2
    Yes. Just import HttpClientModule.
    – Nir Lanka
    Commented Jul 17, 2019 at 6:22
32

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]
})
31

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]
  }));
2
  • Importing HttpClientModule on app.module.ts is not enough to resolve the problem, but I upvote you anyway for reminding me what I missed.
    – Auguste
    Commented Jun 13, 2019 at 15:56
  • Importing HttpClientTestingModule solved the problem in specs Commented Jan 1, 2020 at 10:15
22

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]
22

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.

enter image description here

18

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!

14

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
12

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.

11

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.

10

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 { }
10

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,
    ...
7

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";

2
  • I have the same problema. I looked in App_modules and I do not have http directory in path @angular-->common I run "npm update" I am working with Windows 8.i, nodejs versión 9.7.1. I am Reading Valerio de Sanctis book... what can it be? Thanks
    – Diego
    Commented Mar 19, 2018 at 0:17
  • just run 'npm i' with administrator mode.
    – Nicks
    Commented Jul 26, 2018 at 13:46
7

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
],
7

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

6

Just import the HttpModule and the HttpClientModule only:

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

No need for the HttpClient.

5

In angular github page, this problem was discussed and found solution. https://github.com/angular/angular/issues/20355

1
  • I used this link, wleite,s comment in the bottom of the page for this problem in unit & integration tests with Angular 5
    – FDC
    Commented Sep 6, 2018 at 10:28
4

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.

1
  • Worked for me ..Thanks
    – sam
    Commented Nov 24, 2020 at 2:38
4

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),
  ]
};

2
  • 2
    This works also without modules, using "standalone" approach. Commented Feb 19 at 15:47
  • Yes, you are right if the developer is using the new version of angular. when generating a project will generate it without a modules file that will work, by using the standalone. But in this case, don't forget to add the specific modules for each component separately. Commented Feb 21 at 13:46
3

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.

3

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,

enter image description here

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.

2

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):

enter image description here

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!

1

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

1

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()] };

a screenshot of how I solved the situation

-1
  1. Go to your app.module.ts file.
  2. import HttpClientModule file from '@angular/common/http' e.g import { HttpClientModule } from '@angular/common/http';
  3. Add HttpClientModule in side the imports:[] e.g imports[HttpClientModule]
-1

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 {}

Not the answer you're looking for? Browse other questions tagged or ask your own question.