Nirodha Wickramarathna
Nirodha Wickramarathna

Reputation: 291

Why Angular HTTP Post method Error: Cannot read property 'post' of undefined?

Angular HTTP Post method Error: Cannot read property 'post' of undefined. I am trying to make my first http POST request.But it not working



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);
        }
    );
    
  }

  

}

 

Why this post method not working


Upvotes: 1

Views: 697

Answers (1)

Gabriel Sereno
Gabriel Sereno

Reputation: 855

Nirodha, you need to put the provider in the constructor if you want to use http request:

  1. Import the HttpClient:

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

  2. Put the HttpClient in the constructor:

    constructor(private http: HttpClient){}

  3. In your app.module.ts you need to put in the imports array it:

    imports: [HttpClientModule]

And remember to import at the beginning of your code

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

Upvotes: 1

Related Questions