HTTP POST Request in Angular

Io start sending HTTP calls from our Angular application we need to import the angular/http module and register for HTTP services. It supports both XHR and JSONP requests using HttpModule and JsonpModule respectively. In these article we use HttpModule. We need to import HttpModule in modile.ts file


.........
import { HttpModule } from '@angular/http';

@NgModule({
  imports: [
   HttpModule,
   ............
  ]
  ...........
});



Let’s create Login authentication services using Observable with authLogin Method.


import { Observable } from 'rxjs/Observable';
import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { LoginModel } from '../models/loginmodel';

@Injectable()
export class AuthService {

  constructor(private http: Http) {}

   authLogin(email: string, pwd: string): Observable {

        return this.http.post(APIPATH, JSON.stringify({ email: email, pwd: pwd }))
            .map((res: Response) => res.json())
            .catch(this.handleError);

    }
}

we can use this service in our LoginComponent for authenticate.



.....
import AuthService.

@Component({
  selector: 'page-login',
  templateUrl: './login.html',
})

export class LoginComponent  { 

  
  constructor( ){}

  processLogin(){
      
     this.auth.authLogin(this.email, this.password).subscribe( res => {
       console.log(res);
     }, 
     err => {
        console.log(err);

     });

}

Let’s create login Form when we click on submit it will send data to services and services send data to User API location. from that server we have get JSON response with parameter so we can decide whether Login Success or not.


<form [formGroup]="login" (ngSubmit)="processLogin()">
<div [innerHtml]="serverresponse"></div>
<div class="form-group row">
<div class="col-sm-12">
<input type="email" class="form-control" id="email" name="email" formControlName="email" placeholder="Enter valid e-mail address">
<control-messages [control]="login.controls.email" class="error-msg messages text-left text-danger"></control-messages>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<input type="password" formControlName="password" class="form-control" id="password" name="password" placeholder="Password input">
<control-messages [control]="login.controls.password" class="error-msg messages text-left text-danger"></control-messages>
</div>
</div>
<div class="row m-t-25 text-left">
<div class="col-12">
<div class="checkbox-fade fade-in-primary d-inline-block">
</div>
<div class="forgot-phone text-right f-right">
<a (click)="forgotForm()" class="text-right f-w-600 text-inverse" style="cursor:pointer;"> Forgot Password?</a>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" [disabled]="!login.valid" class="btn btn-primary m-b-0 btn-block">Sign in</button>
</div>
</div>
</form>



Our API send data to PHP file. Lets we have send data to “http://www.eduforbetterment.com/login.php”.


<php
  // php://input is a read-only stream that allows you to read raw data from the request body. From Service we have send data in body so we need to get that data in body then decode that json.


 $inputJSON = file_get_contents('php://input');
 $_POST = json_decode($inputJSON, TRUE); //convert JSON String into array
 //In $_POST now get all data that we send using api.

  // after process we need to return value of that respone
  $response = array();
  $response['loginstatus'] = true;

 echo json_encode( $response);  

Using these simple step you can post data to your server.

Spread the love
  • 34
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •