依赖注入和 httpclient

Dependency Injection & httpclient

我正在尝试了解 Angular 中的 DI 7. DI 用于实例化 class 的对象,该对象被制成可注入的。

需要知道我们如何将其应用于 HttpClient

我知道我们可以像下面这样注入它

constructor(private http: HttpClient) { }

但是我们怎么知道 HttpClient 是可注射的?

问题看起来很傻。由于我是 Angular 的新手,我试图理解其中的逻辑。

基本上,因为当导入 HttpClientModule 时,它告诉 Angular 依赖注入器他可以在需要时提供 HttpClient

这是由

完成的

1) class HttpClient 装饰为 @Injectable()

2) 有一个模块 HttpClientModule 导入,更重要的是 提供 HttpClient.

3) 当然,所有这些都是由 Angular 依赖注入器完成的,它是框架的基本组成部分。它正在查看各种模块及其 providers 配置参数。 (和其他一些相关的,对于 Angular 6+)


如果您想创建自己的可注入服务,您基本上应该执行相同的操作(1 和 2)。


文档和相关 Angular 源代码片段如下:

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:

(第 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

(大约第 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 {
}

(我自己在上面的片段中用 // <- 注释的评论) .


也值得一读:

https://angular.io/guide/glossary#injector

https://angular.io/guide/dependency-injection


一篇关于细节和现代(Angular 6+)注入方式(具有 tree-shaking 功能)的有趣博客:

https://medium.com/@tomastrajan/total-guide-to-angular-6-dependency-injection-providedin-vs-providers-85b7a347b59f

另一个在依赖注入系统(Angular 2)的机制方面更深入:https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html#dependency-injection-in-angular

最后一个更深入的技术: https://blog.angularindepth.com/angular-dependency-injection-and-tree-shakeable-tokens-4588a8f70d5d