找不到'@ angular/common/http'模块 [英] Cannot find the '@angular/common/http' module
问题描述
我正在此关于Angular的有关Http的基础教程.
I am following this fundamental tutorial on Angular about Http.
在设置:安装模块"部分中可以看到,他们按如下所示导入HttpClientModule:
As one can see in the "Setup: Installing the module" section, they import the HttpClientModule as follow:
import {HttpClientModule} from '@angular/common/http';
当我在项目中尝试此操作时,出现以下错误:找不到模块'@ angular/common/http'".
When I try this in my project, I get the following error: "Cannot find module '@angular/common/http'".
我尝试导入以下模块,如下所示:
I have tried importing the following module, as follow:
import { HttpModule } from '@angular/http';
然后是我的导入部分:
imports: [
HttpModule
],
现在的问题是,我无法将此HttpModule注入我的服务对象,并且出现以下错误:找不到模块HttpModule".
The problem now is, I cannot inject this HttpModule into my service object, and I get the following error: "Cannot find module HttpModule".
这是我的服务班级:
import { Injectable, OnInit } from '@angular/core';
//Custom Models
import { Feed } from '../Models/Feed';
@Injectable()
export class FeedsService {
constructor(private httpClient: HttpModule) {}
}
我在做什么错了?
更新
当我意识到我无法按照教程导入模块时,我应该做的就是运行npm update
命令,更新所有软件包.
Update
All I should have done when I realized I could not import the module as per the tutorial, was to run the npm update
command, to update all my packages.
推荐答案
重要:HttpClientModule
适用于Angular 4.3.0及更高版本.检查 @Maximus' 注释和 answer 了解更多信息.
原始答案:
Important: HttpClientModule
is for Angular 4.3.0 and above. Check @Maximus' comments and @Pengyy's answer for more info.
Original answer:
您需要在组件/服务而非模块中注入HttpClient
.如果在@NgModule
You need to inject HttpClient
in your component/service not the module. If you import HttpClientModule
in your @NgModule
// app.module.ts:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
// Import HttpClientModule from @angular/common/http
import {HttpClientModule} from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// Include it under 'imports' in your application module
// after BrowserModule.
HttpClientModule,
],
})
export class MyAppModule {}
所以改变
constructor(private httpClient: HttpModule) {}
到
constructor(private httpClient: HttpClient) {}
文档中所写的内容: https://angular.io/guide/http#making-a-request-for-json-data
但是,由于您导入了HttpModule
However, since you imported the HttpModule
您需要以 @Maximus 中的注释和<
you need to inject constructor(private httpClient: Http)
as @Maximus stated in the comments and @Pengyy in this answer.
有关HttpModule
和HttpClientModule
之间差异的更多信息,请查看以下答案: https://stackoverflow.com/a/45129865/5706293
And for more info on differences between HttpModule
and HttpClientModule
, check this answer: https://stackoverflow.com/a/45129865/5706293
这篇关于找不到'@ angular/common/http'模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!