具有以下代码:
#home.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: HttpClientModule) {}
id: number;
private headers = new Headers({ 'Content-Type': 'application/json' });
person = [];
fetchData = function() {
this.http
.get('http://localhost:5555/person')
.subscribe((res: Response) => {
this.person = res;
});
};
deleteProduct = function(id) {
if (confirm('Are you sure?')) {
const url = `${'http://localhost:5555/person'}/${id}`;
return this.http
.delete(url, { headers: this.headers })
.toPromise()
.then(() => {
this.fetchData();
});
}
};
ngOnInit() {
this.fetchData();
}
}
加载此页面时,在浏览器控制台中出现以下错误:
HomeComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: this.http.get is not a function
at HomeComponent.fetchData (home.component.ts:16)
at HomeComponent.push../src/app/home/home.component.ts.HomeComponent.ngOnInit (home.component.ts:35)
at checkAndUpdateDirectiveInline (core.js:20644)
at checkAndUpdateNodeInline (core.js:21908)
at checkAndUpdateNode (core.js:21870)
at debugCheckAndUpdateNode (core.js:22504)
at debugCheckDirectivesFn (core.js:22464)
at Object.eval [as updateDirectives] (HomeComponent_Host.ngfactory.js? [sm]:1)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:22456)
at checkAndUpdateView (core.js:21852)
为什么.get
在这里失败? vscode并没有向我尖叫。这是angular的版本7。
答案 0 :(得分:5)
您的构造函数参数应该来自 HttpClient
,而不是 HttpClientModule
,
将导入更改为
import { HttpClient } from '@angular/common/http';
和构造函数为
constructor(private http: HttpClient) {}
答案 1 :(得分:0)
HttpClientModule
通常添加到imports
的{{1}}数组中。 NgModule
作为组件,服务或指令等中的依赖项注入。
所以
HttpClient
应该是
constructor(private http: HttpClientModule) {}
位置:constructor(private http: HttpClient) {}
PS:我还要指出的另一件事是,与其编写匿名函数,不如编写匿名函数,因为这更符合《 Angular样式指南》。
所以import { HttpClient } from '@angular/common/http';
应该只是fetchData = function() {...}