Categories
Angular

http post request from angular with example

In this post, we will learn to make http post request from angular with example

To communicate with backend server we are using HttpClient from @angular/common/http

Syntax
this.http.post<return-type>(url: string, body: any, options?);

In this example we are going to save a student details. To do that we need to invoke a http post method with student details

{  
  "firstname": "string", 
  "lastname": "string"
  "department": "string",
}

Now I am creating a model class for above json request like below

export class Student {    
    firstname: string;    
    lastname: string;
    department: string;
}

Now we need to create service class to make http post request from angular
creating service layer command:  ng g s student

import { Injectable } from '@angular/core';

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

  constructor() { }
  
}

Now we can create saveStudent method to save the student details in back end

 /**
   * In this method we are calling http post method 
   * @param student 
   */
  saveStudentDetails(student: Student): Observable<any>{
    return this.http.post<any>('http://localhost:8080/api/student',student);
  }
Student Service layer
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Student } from '../model/student.model';
@Injectable({
  providedIn: 'root'
})
export class StudentService {

  constructor(private http: HttpClient) { }


  /**
   * In this method we are calling http post method 
   * @param student 
   */
  saveStudentDetails(student: Student): Observable<any>{
    return this.http.post<any>('http://localhost:8080/api/student',student);
  }
  
}

Now we can call this service class method from component, For example I am creating a simple form and component as like below

import { Component, OnInit } from '@angular/core';
import { StudentService } from '../../service/student.service';
import { Student } from '../../model/student.model';

@Component({

  selector: 'app-student-details',
  templateUrl: './student-details.component.html',
  styleUrls: ['./student-details.component.css']
})
export class StudentDetailsComponent implements OnInit {

  constructor(private studentService: StudentService) { }

  student: Student=null;

  ngOnInit(): void {   

  }

  saveStudent(){
    //Creating model class
    this.student.firstname="Beginners";
    this.student.lastname="Bug";
    this.student.department="Blooggin";
    
    //Call service layer from component 
    this.studentService.saveStudentDetails(this.student).subscribe(data=>{
      console.log("Student Added successfully");
    
    },error=>{
      console.log("There was some error ",error);
    });

  }

}
<form (ngSubmit)="saveStudent()">
<label>FirstName:</label> <br/><input type="text" name="firstname" placeholder="Enter First name"><br/>
<label>LastName:</label> <br/><input type="text" name="lastname" placeholder="Enter Last name"><br/>
<label>Department:</label> <br/><input type="text" name="department" placeholder="Enter Department"><br/><br/>
<button class="button" type="submit">Add</button>

</form>
Conclusion

We learned to make http post request from angular with example

Related Articles

call http rest service from angular

Categories
Angular

call http rest service from angular

In this tutorial, we will learn to call http rest service from angular

To understand this tutorial we should know the angular basics like components, service

Before starting we should have a component & service knowledge, Here we are going to use appcomponent as component and going to create a service to call http service

Navigate to src/app from vs code terminal, Execute below command to create service

ng g s app-service

app-service.service.ts & app-service.service.spec.ts will get created in src/app folder

C:\Users\Admin\angular-demo\src\app>ng g s app-service
CREATE src/app/app-service.service.spec.ts (378 bytes)
CREATE src/app/app-service.service.ts (139 bytes)

C:\Users\Admin\angular-demo\src\app>

Now open the app-service.ts file

import { Injectable } from '@angular/core';

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

  constructor() { }
}
Http Endpoint details

For this tutorial, I have created a endpoint which return student details

http://localhost:8080/api/student
Output Json
[
  {
    "id": 1,
    "department": "ECE",
    "firstname": "rajesh",
    "lastname": "kumar"
  }
]

Create a student model class to map the HTTP Response

student.model.ts

export class Student {
    department: string;
    firstname: string;
    id: number;
    lastname: string;
}

create a method to invoke http call. We are using HttpClient from @angular/common/http

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Student } from './model/student.model';


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

  constructor(private http: HttpClient) { }

  getStudentDetails(): Observable<Student[]>{
    return this.http.get<Student[]>('http://localhost:8080/api/student');

  }

}

Now call the getStudentDetails() method from app.component.ts on ngOnInit

  ngOnInit(): void {
    this.appService.getStudentDetails().subscribe(data => {
      this.studentDetails=data;
    });

Below is the complete app.component.ts

import { Component } from '@angular/core';
import { AppServiceService } from './app-service.service';
import { Student } from './model/student.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  title = 'angular-demo';

  constructor(private appService: AppServiceService) { }

   studentDetails: Student[];

  ngOnInit(): void {
    this.appService.getStudentDetails().subscribe(data => {
      this.studentDetails=data;
    });

  }
}

You can map this StudentDetails to your html as like below

<div *ngIf="studentDetails">
    <table>
        <thead>
            <tr>
                <td>ID</td>
                <td>FirstName</td>
                <td>LastName</td>
                <td>Department</td>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let response of studentDetails">
                <td>
                    {{response.id}}
                </td>
                <td>
                    {{response.department}}
                </td>
                <td>
                    {{response.firstname}}
                </td>
                <td>
                    {{response.lastname}}
                </td>
            </tr>

        </tbody>

    </table>

</div>
<router-outlet></router-outlet>
Conclusion

I this post we learned to call http rest service from angular

Github

https://github.com/rkumar9090/angular-demo/blob/master/src/app/app-service.service.ts