Alain Bressers Alain Bressers - 17 days ago 8
TypeScript Question

AngularJS 2 - Using HTTP Wrapper - Getting "No Provider!" Error

For one of our projects, I need to use an HTTP wrapper that will send an authorisation header with every request. However, upon loading the page with

npm start
, I get the following error in console:

EXCEPTION: Error in http://localhost:3000/app/app.component.html:2:2 caused by: No provider for HttpClient!
ORIGINAL EXCEPTION: No provider for HttpClient!


Note: for the sake of not pasting all the code, I use dots ("...") to represent "self-explanatory" things such as importing the core libraries, etc.
I'm also using "placeholder" to replace names that I cannot disclose.

For the wrapper I'm using, I found the following:

http.wrapper.ts:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';

@Injectable()
export class HttpClient {
...
}


In my API service, I do the following to make use of the HTTP wrapper:

api.service.ts:

import { Injectable, OnInit } from '@angular/core';
import { Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import { HttpClient } from '../http.wrapper';

@Injectable
export class APIService implements OnInit {
...

constructor(private httpClient: HttpClient) {}

getActiveScenarios(): Observable<Scenario[]> { ... }
}


app.module.ts:

...
import { HttpClient } from './common/http.wrapper';
import { MyModule } from './placeholder/my-module.module';
...

@NgModule({
imports: [BrowserModule, MyModule],
declarations: [AppComponent],
exports: [AppComponent, BrowserModule],
bootstrap: [AppComponent]
})
export class AppModule {}


my-module.component.ts:

import { ApiService } from '../placeholder/services/api.service';

@Component({
moduleId: module.id,
selector: 'placeholder',
templateUrl: './my-module.component.html',
providers: [ ApiService ]
})
export class MyModuleComponent implements OnInit {
constructor(private apiService: ApiService) {}

ngOnInit() {}

...
}

Answer

Add HttpClient to module's list of providers to register it with the injector.

app.module.ts

...
import { HttpClient } from './common/http.wrapper';
import { MyModule } from './placeholder/my-module.module';
...

@NgModule({
   imports: [BrowserModule, MyModule],
   declarations: [AppComponent],
   exports: [AppComponent, BrowserModule],
   providers: [HttpClient],
   bootstrap: [AppComponent]
})
export class AppModule {}
Comments