typescript - 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
只需导入一次模块,我就可以在整个项目中使用。
解决方案
根据Angular的官方文档HttpClientModule
,不需要在view.module.ts
你的AppModule.ts
.
这是该网站的报价:
在您可以使用 HttpClient 之前,您需要导入 Angular
HttpClientModule
。大多数应用程序都在根 AppModule 中执行此操作。导入HttpClientModule
AppModule 后,您可以将其注入HttpClient
到应用程序类中,如下ConfigService
例所示。
推荐阅读
- python - 无法从 Python 中的字符串替换/删除 \xa0(从 Excel 解析)
- python - Dockerized django 应用程序不在浏览器中运行
- json - Apache HTTP 客户端中的请求 POST 失败
- python - 如何使用熊猫将字符串转换为时间戳
- mongodb - mongo $or/$and 带有两个用于地理查询的选择器
- prometheus - 如何按标签计算量规指标的百分比?
- robotframework - 如何在python中将SQL查询的结果存储为字符串
- blockchain - Truffle 开发错误“Greeter 的当前网络 ID 没有网络配置”
- makefile - 如何推导出make产生的error的含义?
- c# - 无法反序列化 SecurityIdentifier 类