我通过运行 ng new first-project
安装了一个基础的 Angular 6 项目,并获得了默认的应用程序模块和组件。现在,我通过运行 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 { }
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。
HttpInterceptors
实例,请仅在您的AppModule
中导入HttpClientModule
,并将拦截器添加到根应用程序注入器中。如果您在不同的模块中多次导入HttpClientModule
(例如,在延迟加载模块中),每个导入都会创建一个新的HttpClientModule
副本,这将覆盖根模块中提供的拦截器。 - darko99