angular 4 httpclient put example


Angular 4 HttpClient put example

angular 4 HttpClient put example , here in this post we will learn how to update some record on the basis of primary key.

So let’s take one student example and let’s update student record on the basis of student id.

We will be using HttpClient class put method along with RxJS Observables.

Let’s take create service and component class to call Rest Api with student object.

  1. student.service.ts
  2. student.component.ts

student.service.ts

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

@Injectable()
export class StudentService {
   BASE_URL="/api/"
   API_UPDATE_STUDENT_URL = this.BASE_URL + "update/student";
   constructor(public http: HttpClient) { }
   
   updateStudent(id: string, student: Student) {
      return this.http.put<any>(this.API_UPDATE_STUDENT_URL + "/" + id, student);
   }
}

student.component.ts

import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { StudentService } from './student.service';
import { Student } from '../customer/student.model';

@Component({
  selector:'student',
  templateUrl:'./student.html'
})

export class StudentComponent {
  public student = new Student();
  constructor(private studentService: StudentService) { }
  ngOnInit() {
    this.student.roll = "s-102";
    this.student.name = "Vikas Kumar";
    this.updateStudent("s-101", this.student);
  }

   updateStudent(id: string, student: Student) {
      this.studentService.updateStudent(id, student).subscribe(
      (data: any) => console.log(data),
      (err: any) => console.log(err),
      () => console.log("--------Done--------")
    );
  }   
}

Here student service will be calling below Rest Api.

package com.javagf.api;

import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.javagf.vo.StudentVO;

@Path("/api/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class StudentApiImpl {
  
  @Path("update/student/{id}")
  @PUT
  public Response updateCustomer(@PathParam("id") String id) {
     System.out.println("-----update student request------");
     return Response.noContent().build();
  }
}

 






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229