How to make a post request with angular 5

Let’s give this a try…

//FileName: login.service.ts
import { Injectable } from '@angular/core';
import { HttpParams, HttpClient, HttpHeaders } from '@angular/common/http';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

import { catchError, retry } from 'rxjs/operators';

@Injectable()
export class LoginService {
    private _loginUrl="http://1.2.3.4/signin"; //the api url where we need to make a call
    constructor(private _http: HttpClient) {} //this initialized the HttpClient which we use to do a post or get call

    //setting body of the parameters to send via post 
    private body = new HttpParams()
    .set('username', 'onetap')
    .set('password', '123456');

    checkLogin(){
         return this._http.post(this._loginUrl,
            this.body.toString(),
            {
              headers: new HttpHeaders()
                .set('Content-Type', 'application/x-www-form-urlencoded')
            }
          )
        .pipe(
        catchError(this.handleError) // then handle the error
       );
    }
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }
}

Let me explain this now…
First things first… go and refer this link , which is the basic guide with live example on how setup httpclient and use it.

In this code lets start with imports:
Injectable: A decorator which will help you inject this service into any component you need. Just import then set it in @Component providers then create instance of it in constructor and use it using this.

HttpParams: Set the parameter or data to send for ‘Content-Type’: ‘application/x-www-form-urlencoded’.

HttpClient: This is the module using which we implement the get, post put methods.

throwError, catchError, retry: This could be your homework to research on.

checkLogin() implements the post method. Using HttpParams we create the body instance and pass it to checkLogin.
Post request will take 3 parametes. 1. Url, 2. Data or body to send, 3. Optional headers.

Now we call this checkLogin from our components onSubmit method given below

    onSubmit() {
        this.loginService.checkLogin()
        .subscribe(resp => {
            this.user = {
                username: resp['username'],
                email: resp['email'],
                password: resp['password']
            };
            console.log(this.user);//Check if we are getting data from server
        });
                

    }

After all this is done. If you are getting a CORS issue which you might get if you are on local host or a different server. Use the code below

This is at the server end code

do

npm install cors --save

and just add these lines in your main file where your request is going.

const cors = require('cors');
const express = require('express');
let app = express();
app.use(cors());
app.options('*', cors());

Leave a Comment