1

I have implemented a simple angular application that has a component that calls a service which in turn calls an api. I have registered the service in the provider of the app module but getting the following error .

 NullInjectorError: No provider for HttpClient

I have created a stackblitx to replicate the issue

stackblitz

Code

service

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';
const httpPostOptions = {

    headers:
        new HttpHeaders(
            {
                'Content-Type': 'application/json; charset=utf-8',
            }),
    withCredentials: true,
}


@Injectable({
    providedIn: 'root'
})
export class AbcCommonService {

    webApplication = this.getApiLocation();

    private getApiLocation() {
        return location.protocol + '//' + location.hostname;
    }

    constructor(private httpClient: HttpClient) { }

    httpGet(url: string): Observable<any> {
        return this.httpClient.get(this.webApplication + url, httpPostOptions)
            .pipe(map((response: Response) => {
                return response;
            }), catchError(error => {
                this.onError(error);
                return Promise.reject(error);
            }));
    }




}

App module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http'; 
import { AbcCommonService } from './shared/abc.common.service';
import { AppComponent } from './app.component';
import { ListWrapperComponent } from './list-wrapper/list-wrapper.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, ListWrapperComponent ],
  bootstrap:    [ AppComponent ],
  providers: [AbcCommonService ],
})
export class AppModule { }
Edgar
  • 6,022
  • 8
  • 33
  • 66
Tom
  • 8,175
  • 41
  • 136
  • 267
  • 1
    Add `HttpClientModule` to the `imports` arrays in the *app.module.ts*, just like all the other modules you import! – R. Richards Aug 20 '19 at 16:47
  • 1
    Please make an effort to even google. Took me one second to find that duplicate ;) – AT82 Aug 20 '19 at 16:55

1 Answers1

2

Add

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

@NgModule({
  imports:      [ HttpClientModule ]
})

inside app.module.ts

Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57