Angular 6:为什么即使没有导入HttpClientModule,HttpClient也能够工作?

4

我通过运行 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中导入了它,并且我直接在view.component.ts中导入了HttpClient,甚至成功得到了响应。为了测试是否经常发生这种情况,我从view.module.ts中删除了FormsModule的导入,以查看我在view.component.html中使用的[(ngModel)]是否仍然有效,因为我已经在app.module.ts中导入了FormsModule,但它不起作用。
我的问题是为什么HttpClientModule让我在不同的模块中导入和使用它,而其他模块却不能这样工作?我试图在网上找到原因,但找不到。有人能告诉我原因吗?谢谢。
附加信息: 1. 如果我没有在任何地方导入HttpClientModule,则HttpClient不起作用。因此,该模块需要在项目中的某个地方导入。 2. 另一种方法也可以工作,即通过在view.module.ts中导入该模块并在app.component.ts中使用它。这意味着,我只需导入该模块一次即可在整个项目中使用HttpClient。
1个回答

3
根据 Angular 的官方文档,在你的view.module.ts中不需要引入 HttpClientModule,只要在你的AppModule.ts中引入即可。
以下是该网站的一句话:
“在使用 HttpClient 之前,您需要导入 Angular 的 HttpClientModule。大多数应用程序都会在根 AppModule 中这样做。 将 HttpClientModule 导入 AppModule 后,可以像以下示例中的 ConfigService 示例那样将 HttpClient 注入到应用程序类中。”

2
我来到这里的原因是 http.d.s 的评论:为了在整个应用程序中使用相同的 HttpInterceptors 实例,请仅在您的 AppModule 中导入 HttpClientModule,并将拦截器添加到根应用程序注入器中。如果您在不同的模块中多次导入 HttpClientModule(例如,在延迟加载模块中),每个导入都会创建一个新的 HttpClientModule 副本,这将覆盖根模块中提供的拦截器。 - darko99
我目前的经验是,即使没有在任何特性模块或应用程序模块中导入HttpClientModule,服务中注入HttpClient也能正常工作...没有问题...这是否有效?如果不导入HttpClientModule并使用HttpClient是否有问题? - Gerros

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接