Angular调用HTTP Post报错Cannot read property 'post' of undefined是什么原因
问题原因
报错Cannot read property 'post' of undefined的直接原因是你没有在组件中正确注入Angular的HttpClient服务,导致this.http为未定义值,无法调用其下的post方法。
修复步骤
- 第一步:在项目根模块(通常是
app.module.ts)中导入并注册HttpClientModule,全局启用HTTP请求能力:
// app.module.ts 顶部导入 import { HttpClientModule } from '@angular/common/http'; @NgModule({ // 其他配置省略 imports: [ // 其他已导入的模块 HttpClientModule ] }) export class AppModule { }
- 第二步:在当前
RegisterComponent组件中导入依赖,并在构造函数中注入HttpClient服务:
// 组件顶部导入依赖 import { HttpClient } from '@angular/common/http'; import { HttpParams } from '@angular/common/http'; export class RegisterComponent implements OnInit { firstnameControl = new FormControl(); hide=true; // 构造函数注入HttpClient constructor(private http: HttpClient) { } ngOnInit(): void { } signup(){ let body = new HttpParams({ fromObject:{ 'firstname': this.firstnameControl.value, } }); var url = "http://52.15.72.215:3000/api/user"; this.http.post(url, body).subscribe( (data: any) =>{ alert(data); } ); } }
- 补充注意:如果后端要求
application/x-www-form-urlencoded格式的参数,使用HttpParams包装是正确的;如果后端接收JSON格式的请求体,直接传入普通JS对象即可,不需要用HttpParams包装。
内容的提问来源于stack exchange,提问作者Nirodha Wickramarathna
相关产品推荐
相关产品推荐

