Basically, because when HttpClientModule
is imported, it tells to the Angular dependency injector that he can provide an HttpClient
when needed.
This is done by
1) Having a class HttpClient
decorated as @Injectable()
2) Having a module HttpClientModule
which imports and, more importantly, provides the HttpClient
.
3) Of course all is done by Angular dependency injector, which is a fundamental brick of the framework. It is doing the work of looking at the various modules and their providers
config parameter. (and some other related, for Angular 6+)
You should basically do the same (1 and 2) if you want to create your own injectable services.
Documentation and relevant Angular source code snippets below :
https://angular.io/api/common/http/HttpClientModule
HttpClientModule
Configures the dependency injector for HttpClient with supporting
services for XSRF. Automatically imported by HttpClientModule.
source code for HttpClient:
(around line 56)
/**
* Perform HTTP requests.
*
* ....
*/
@Injectable() // <- this marks the class as Injectable (which basically makes it a Service in Angular framework)
export class HttpClient {
// ...
Source code for HttpClientModule
(around line ~143)
@NgModule({
/**
(...)
* Configures the [dependency injector](guide/glossary#injector) where it is imported
* with supporting services for HTTP communications.
*/
providers: [
HttpClient, // <- here this is how the injector system is aware of HttpClient being injectable, if you import this module
(...)
]
})
export class HttpClientModule {
}
(my own comments in above snippets noted with // <-
)
.
Also worth reading :
https://angular.io/guide/glossary#injector
https://angular.io/guide/dependency-injection
One nice interesting blog about the details, and the modern (Angular 6+) way of doing injection (with tree-shaking capabilities) :
https://medium.com/@tomastrajan/total-guide-to-angular-6-dependency-injection-providedin-vs-providers-85b7a347b59f
Another that goes more in the mechanics of the dependency injection system (of Angular 2) : https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html#dependency-injection-in-angular
And a last one that goes a bit more deep technical :
https://blog.angularindepth.com/angular-dependency-injection-and-tree-shakeable-tokens-4588a8f70d5d