首页 > 解决方案 > Angular 6:为什么即使不导入 HttpClientModule HttpClient 也能工作?

问题描述

我通过运行安装了一个准系统 Angular 6 项目ng new first-project,我得到了一个默认的应用程序模块和组件。现在我通过运行ng generate module view和创建了一个新模块和一个组件ng 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 { }

视图.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);
        });
    }

}

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

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

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

标签: typescriptangular6angular-httpclientangular-module

解决方案


根据Angular的官方文档HttpClientModule,不需要在view.module.ts你的AppModule.ts.

这是该网站的报价:

在您可以使用 HttpClient 之前,您需要导入 Angular HttpClientModule。大多数应用程序都在根 AppModule 中执行此操作。导入HttpClientModuleAppModule 后,您可以将其注入HttpClient到应用程序类中,如下ConfigService例所示。


推荐阅读