首页 > 解决方案 > 为什么 Angular HTTP Post 方法错误:无法读取未定义的属性“post”?

问题描述

Angular HTTP Post 方法错误:无法读取未定义的属性“post”。我正在尝试发出我的第一个 http POST 请求。但它不起作用



export class RegisterComponent implements OnInit {
  [x: string]: any;

firstnameControl = new FormControl();  //To get values


  hide=true;
  constructor( ) { }

  ngOnInit(): void {
  }


  signup(){
    //1.Collect Parameters
    let body = new HttpParams({
      fromObject:{
          'firstname': this.firstnameControl.value,
      }
    });
    
    //2.Send to URL
    var url ="http://52.15.72.215:3000/api/user";
    this.http.post(url ,body).subscribe(
      ( data: any) =>{
          alert(data);
        }
    );
    
  }

  

}

 

为什么这个帖子方法不起作用


标签: node.jsangularpost

解决方案


Nirodha,如果要使用 http 请求,则需要将提供程序放在构造函数中:

  1. 导入 HttpClient:

    从“@angular/common/http”导入 { HttpClient };

  2. 将 HttpClient 放入构造函数中:

    构造函数(私有 http:HttpClient){}

  3. 在您的 app.module.ts 中,您需要将其放入 imports 数组中:

    进口:[HttpClientModule]

并记住在代码的开头导入

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

推荐阅读