angular - 找不到 '@angular/common/http' 模块

标签 angular node-modules

我正在关注 this关于 Http 的 Angular 基础教程。

正如在“设置:安装模块”一节中看到的,他们按如下方式导入 HttpClientModule:

import {HttpClientModule} from '@angular/common/http';

当我在我的项目中尝试这个时,我收到以下错误:“找不到模块‘@angular/common/http’”。

我已经尝试导入以下模块,如下所示:

import { HttpModule } from '@angular/http';

然后是我的导入部分:

imports: [
    HttpModule
],

现在的问题是,我无法将此 HttpModule 注入(inject)到我的服务对象中,并且出现以下错误:“找不到模块 HttpModule”。

这是我的服务等级:

import { Injectable, OnInit } from '@angular/core';
//Custom Models
import { Feed } from '../Models/Feed';

@Injectable()
export class FeedsService {
    constructor(private httpClient: HttpModule) {}
}

我做错了什么?

更新 当我意识到我无法按照教程导入模块时,我应该做的就是运行 npm update 命令来更新我的所有包。

最佳答案

重要:HttpClientModule 适用于 Angular 4.3.0 及更高版本。查看 @Maximus' 评论和 @Pengyy's answer 了解更多信息。


原答案:

您需要在您的组件/服务而不是模块中注入(inject) HttpClient。如果您在 @NgModule

中导入 HttpClientModule
// 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) {}

因为它已经写在 documentation


但是,由于您导入了 HttpModule

您需要注入(inject) constructor(private httpClient: Http),如评论中的 @Maximus@Pengyy 中的 this answer 所述。

有关 HttpModuleHttpClientModule 之间差异的更多信息,请查看 this answer

关于angular - 找不到 '@angular/common/http' 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45207615/

相关文章:

Angular 4在重新路由到它时调用组件方法

css - 如何应用像:hover to ng2 pseudo class :host这样的伪类

angular - 如何使用 Angular CLI + ng-packagr + state mgmt 构建 Angular 4 组件库?

node.js - Loopback - 模型 ACL 列表在数据库中查找,而不是在其 json 文件中查找

javascript - 执行 webpack.config 时出错 - 无法解析 'es6-promise'

json - form builder angular 2 - 如何构建控件数组?

angular - 我们可以控制 ViewEncapsulation.None 影响 Angular 应用程序中的其他组件吗?

angular - 如何在 Ionic 2 中使用 angular 2 服务?

node.js - docker中具有只读源文件的可写node_modules

javascript - 即使在 Node.js 中的回调函数之后,函数也会异步运行