Bárbara Peres
Bárbara Peres

Reputation: 595

Ng Component withTypeError: Cannot read property 'post' of undefined

I've built two components: signup and signup-form.

Signup-form looks like this.

After filling up the form and clicking the Submit button I get:

error

I've searched through all the questions with similar problem and none of them helped me fix the blocker.

Signup.component.html has the sign-up form component:

(...)
<app-signup-form></app-signup-form>
(...)

Signup-form.component.html:

<form [formGroup]="mysignup">
  <div class="form-group">
    Name:<br>
    <input type="text" formControlName="name" ngModel="name"  required/>
  </div>
  <div class="form-group">
    Email:<br>
    <input type="email" formControlName="email" ngModel="email"  required/>
  </div>
  <div class="form-group">
      Password:<br>
      <input type="password" formControlName="password" ngModel="password" required/>
  </div>
  <div class="form-group">
      <input type="button" value="Submit" class="btn btn-primary" (click)="signupUser()" />
  </div>
  <br><br>
  <pre>{{mysignup.value | json}}</pre>
</form>

Signup-form.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms'; // Linking the form model to the form template
import { HttpClient, HttpResponse } from '@angular/common/http';

@Component({
  selector: 'app-signup-form',
  templateUrl: './signup-form.component.html',
  styleUrls: ['./signup-form.component.scss']
})
export class SignupFormComponent implements OnInit {
  mysignup: FormGroup;
  constructor() {}
  ngOnInit() {
    this.mysignup = new FormGroup({
      name: new FormControl('', Validators.required),
      email: new FormControl('', Validators.required),
      password: new FormControl('', Validators.required)
  });
  }
  signupUser($scope, $http) {
    this.mysignup = new FormGroup({
      name: new FormControl('', Validators.required),
      email: new FormControl('', Validators.required),
      password: new FormControl('', Validators.required)
  });
  // tslint:disable-next-line:no-debugger
  // debugger;
    $http.post('test.php', {
      'name': $scope.name,
      'email': $scope.email,
      'password': $scope.mysignup.password
    }).then(function(Response) {
      console.log('Data inserted successfully');
    }, function(error) {
      alert('Sorry! Data couldnt be inserted!');
      console.error(error);
    });
  }
}

I just want the data to arrive test.php because from there onward I know how to handle.

How to fix this?

Upvotes: 2

Views: 735

Answers (2)

Niladri Basu
Niladri Basu

Reputation: 10614

You dont have http in your code. Change your constructor to this:

First, import http like this: import { HttpClient } from "@angular/common/http";

Then declare a local variable named http in your constructor like this:

constructor(private http: HttpClient) { }                    

Also, it's a standard practice to use http instead of $http.

And do NOT pass $http and $scope to signupUser function. Within signupUser function access the form values like this: this.formGroupName.controls['formControlName'].value (In your case this.mysignup.controls['name'].value).

Then, you can call the signupUser from html like:

 <button (click)="signupUser()">Sign UP<button>                        

You'll have to change your post call like this (NOTE: http.post returns an Observable so you'll have to subscribe to it like this):

this.http.post('test.php', {
  'name': this.mysignup.controls['name'].value,
  'email': this.mysignup.controls['email'].value,
  'password': this.mysignup.controls['password'].value
}).subscribe(function(Response) {
  console.log('Data inserted successfully');
}, function(error) {
  alert('Sorry! Data couldnt be inserted!');
  console.error(error);
});                         

Please note: It is advisable to write all the HttpClient related(get, post, etc..) codes separately in service file.

Upvotes: 2

Giacomo Vo&#223;
Giacomo Vo&#223;

Reputation: 1067

Looks like you are too much in old Angular 1.x patterns there. The error comes from the line with $http.post, because you injected the $http service in the signupUser method. You will need to inject it into the constructor of your component class

constructor(protected $http: HttpClient) {}

and then access it in the class' methods with

this.$http.post(...)

Don't forget to import CommonModule in the @Module declaring this component.

More info about dependency injection in the Angular docs: https://angular.io/guide/dependency-injection-pattern

Also consider to overthink your variable naming, because the $ sign is not used for this case in Angular 2+, and don't use $scope, but data bindings.

Upvotes: 0

Related Questions