Angular 6:为什么即使不导入 HttpClientModule,HttpClient 也能正常工作?

Angular 6: Why does HttpClient work even without importing HttpClientModule?

我通过 运行 ng new first-project 安装了一个准系统 angular 6 项目,我得到了一个默认的应用程序模块和组件。现在我通过 运行 ng generate module viewng generate component view/view 创建了一个新模块和其中的一个组件。 现在我的 app.module.ts 看起来像这样

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TestService } from './test.service';
import { ViewModule } from './view/view.module';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        FormsModule,
        HttpClientModule,
        ViewModule
    ],
    providers: [
        TestService
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

view.module.ts

import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { ViewComponent } from './view/view.component';

@NgModule({
    declarations: [ViewComponent],
    imports: [
        CommonModule,
        FormsModule
    ],
    exports: [
        ViewComponent
    ]
})
export class ViewModule { }

view.component.ts

import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {

    username: string = "";
    response: any;

    constructor (private http: HttpClient) { }

    search () {
        this.http.get('https://api.github.com/users/' + this.username)
        .subscribe((response) => {
            this.response = response;
            console.log(this.response);
        });
    }

}

所以问题是,我没有在 view.module.ts 中导入 HttpClientModule 而是在 app.module.ts 中导入 HttpClientModule 并且我直接在 [=39] 中导入了 HttpClient =] 我什至成功地得到了回应。 为了测试这种情况是否经常发生,我从 view.module.ts 中删除了 FormsModule 导入,以查看我在 view.component.html 中使用的 [(ngModel)] 是否仍然有效,因为我已经导入 FormsModule 在 app.module.ts 里面,但它没有。

我的问题是为什么 HttpClientModule 让我导入它并在不同的模块中使用它,为什么其他模块不能那样工作? 我试图在网上找到原因,但没有找到。谁能告诉我原因吗?谢谢。

附加信息: 1. 如果我不在任何地方导入 HttpClientModuleHttpClient 将不起作用。 所以模块需要在项目的某个地方导入。 2. 它也以另一种方式工作,即通过在 view.module.ts 中导入模块并在 app.component.ts 中使用它。这意味着,只需导入一次模块,我就可以在整个项目中使用 HttpClient

根据 Angular 的 official document,不需要在 view.module.ts 中导入 HttpClientModule,只要在 [=12] 中导入即可=].

以下是该网站的引述:

Before you can use the HttpClient, you need to import the Angular HttpClientModule. Most apps do so in the root AppModule. Having imported HttpClientModule into the AppModule, you can inject the HttpClient into an application class as shown in the following ConfigService example.