为什么要在 app.module.ts 中导入 { HttpClientModule } [英] Why to import { HttpClientModule } in app.module.ts

查看:30
本文介绍了为什么要在 app.module.ts 中导入 { HttpClientModule }的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直致力于创建一个服务来发出 http 请求,因此我使用的是 Angular 提供的 HttpClientModule.我有 data.serivce.ts 文件,其中声明了服务,我正在导入 HttpClient,如下所示.

I have been working on creating a service to make http requests and hence I'm using HttpClientModule given by Angular. I have data.serivce.ts file where the service is declared and I'm importing the HttpClient as shown below.

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

@Injectable()
export class DataService {

  constructor(private http:HttpClient) { 

  }

  validateLogin(){
    return this.http.get('https://someurl')
  }
}

由于我在app.module.ts的providers数组中注入了DataService的依赖,不明白为什么还要在app.module.ts中再次导入HttpClientModule

推荐答案

您应该研究 Angular 模块的工作原理.您的 app.module.ts 包含 AppModule,它是一个根模块.每个应用程序至少有一个模块,即根模块.如果您在 AppModule 中导入任何模块,那么您的应用程序的每个组件都可以访问其(导入的模块)组件.

You should look into how angular modules work. Your app.module.ts contains AppModule which is a root module. Every application has at least one module i.e. root module. If you import any module inside your AppModule then its (imported module) components will be accessible to every component of your application.

这就是让 HttpClient 在应用程序中无处不在"可用的原因:

Thats why to make HttpClient available "everywhere" in the app:

在 AppModule 中导入 HttpClientModule.现在,您可以在自己的服务或组件中使用 HttpClientModule 中定义的服务、组件等.

import the HttpClientModule inside AppModule. Now you can use Services, Components etc defined inside HttpClientModule in your own services or components.

这篇关于为什么要在 app.module.ts 中导入 { HttpClientModule }的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆