I have a service that wraps HttpClient. That service is called by a component. The problem is that when I inject the service in the component constructor it is undefined. Moreover, the service constructor seems to not execute at all as a console.log does not print anything. Any ideas?
@Injectable({
providedIn: 'root'
})
export class MyHttpService {
constructor(public httpx: HttpClient) {
console.log("in the constructor - " + this.httpx) // <-- this is never printed
}
call () {
let reqData = { act: 'R'};
this.httpx.post('/myurl', reqData).subscribe(result => {
console.log(result);
}, error => console.log('There was an error: '));
}
}
The related module is defined as follows:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';
import { MyHttpService } from './http.service';
@NgModule({
imports: [
CommonModule,
HttpClientModule,
HttpClient
],
declarations: [
MyHttpService
],
exports: [
MyHttpService
]
})
export class CoreServiceModule {}
The component that calls the service:
@Component({
selector: 'some-selector',
templateUrl: 'some-url.html'
})
export class MyComponent implements OnInit{
constructor(public http:MyHttpService){
console.log(http); // <-- this prints undefined
}
ngOnInit() {
let x = this.http.call(); // <-- this fails as http is undefined
}
}
And the component module:
@NgModule({
declarations: [MyComponent],
exports: [MyComponent],
imports: [BrowserModule, CoreServiceModule],
bootstrap: [MyComponent]
})
export class MyModule {}
forRoot()method that returns an object with at leastngModuleandprovidersproperty.