Angular 4 HttpClient get example


Angular 4 HttpClient get example

Angular 4 HttpClient get example , here in this post i will discuss about HttpClient get method and we will get to know that how to get JSON response from Rest Server Api.

We will be using Angular HttpClient 4.3 and RxJS 5.4 version.

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

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

student.service.ts

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

@Injectable()
export class StudentService {
   BASE_URL="/api/"
   API_GET_STUDENT_URL = this.BASE_URL+"get/student";
   public student = new Student();
   
   constructor(public http: HttpClient) { }

   getStudent(): Observable<Student> {
      return this.http.get<Student>(this.API_GET_STUDENT_URL);
   }
}

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.getStudent();
  }

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

Here student service will will calling below Rest Api.

package com.javagf.api;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.google.gson.Gson;
import com.javagf.vo.StudentVO;

@Path("/api/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class StudentApiImpl {

  @Path("get/student")
  @GET
  public Response getStudent() {
    Gson gson = new Gson();
    StudentVO s = new StudentVO();
    s.setRoll("s-101");
    s.setName("Vikas");
    return Response.status(201).entity(gson.toJson(s)).build();
  }

}






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