Currently, I am in need of using an HTTP wrapper for a specific project that requires sending an authorization header with each request. However, when attempting to load the page using npm start
, an error is displayed in the 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!
To simplify, I have used dots ("...") to represent self-explanatory code and placeholders to conceal certain information.
The chosen HTTP wrapper looks like this:
http.wrapper.ts:
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
@Injectable()
export class HttpClient {
...
}
In order to utilize the HTTP wrapper in my API service, I implement the following:
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() {}
...
}