Angular 4-找不到名称"HttpClient" [英] Angular 4 - Cannot find name 'HttpClient'
问题描述
我正在尝试访问JSON
供稿,但是在文档中进行了更改之后>我收到以下错误
I'm trying to access a JSON
feed but after making the changes from the documentation I get the following error
找不到名称'HttpClient'"
"Cannot find name 'HttpClient'"
我已经看过本教程几次,但我一直在努力寻找为什么会出现此错误的原因.
I've looked over the tutorial a few times but I'm struggling to find why I get this error.
我执行Http请求的组件.
My component where I perform the Http request.
rooms.parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
/.../
})
export class RoomParentComponent implements OnInit {
results: string[];
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
// Make the HTTP request:
this.http.get(/.../).subscribe(data => {
this.results = data;
});
}
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {HttpClientModule} from '@angular/common/http';
import { AppComponent } from './app.component';
import { RoomParentComponent } from './rooms.parent.component';
@NgModule({
declarations: [
AppComponent,
RoomParentComponent
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
如何解决以上错误并将HttpClient注入到构造函数中?
How do I resolve the above error and inject the HttpClient into the constructor?
我的Angular版本是4.3.2
My Angular version is 4.3.2
推荐答案
HttpClient
在Angular 4.3.0
版本中引入.另外,您还必须确保已导入&在主AppModule
的imports
元数据中注入了HttpClientModule
.
HttpClient
got introduced in Angular 4.3.0
version. Also you have to make sure you have imported & injected HttpClientModule
in your main AppModule
's imports
metadata.
// Import HttpClientModule from @angular/common/http in AppModule
import {HttpClientModule} from '@angular/common/http';
//in place where you wanted to use `HttpClient`
import { HttpClient } from '@angular/common/http';
这篇关于Angular 4-找不到名称"HttpClient"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!