How to make a post request with angular 8

Make a post request with angular 8, the example codes.

add Component:

ng g service services/examplePostRequest

add Service :

ng g component examplePostRequest

service file:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ExamplePostRequestService {

  private exampleApiUrl: string = "https://jsonplaceholder.typicode.com/users";

  constructor(private http: HttpClient) { }

  postRequest() {
    let headers = new HttpHeaders({
      'Content-Type': 'application/json',
    })

    return this.http.post(this.exampleApiUrl, {
      var1: 'value1',
      var2: 'value2'
    }, {
        headers: headers
      }
    );
  }
}

component file:

import { ExamplePostRequestService } from './../services/example-post-request.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-example-post-request',
  templateUrl: './example-post-request.component.html',
  styleUrls: ['./example-post-request.component.scss']
})
export class ExamplePostRequestComponent implements OnInit {

  constructor(private service: ExamplePostRequestService) { }

  ngOnInit() {
    this.service.postRequest().subscribe(
      (success) => {
        console.log('success', success);
      },
      (error) => {
        console.log('error', error);
      }
    )
  }

}

add your component file in your routing file (default ‘app-routing.module.ts’), example:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ExamplePostRequestComponent } from './example-post-request/example-post-request.component';

const routes: Routes = [
  {
    path: '',
    component: ExamplePostRequestComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

from the terminal run:

ng serve

and navigate to http://localhost:4200/ , check work in debug console

Debug Console
Debug Console

Leave a Reply

Your email address will not be published. Required fields are marked *