1

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


2
  • well seems this.http is undefined, as the error states. Please provide a minimal reproducible example Commented May 13, 2021 at 16:05
  • Compile is successfully but does not pass the data Commented May 13, 2021 at 16:11

1 Answer 1

1

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";
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that is work after defining constructor(private http: HttpClient){}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.