Angular 5 Observables to get data from an API


Angular 5 Observables to get data from an API

Angular 5 Observables to get data from an API, Here in this post we will learn how to call Java Rest Api using Angular 5 Observables to get Json as response data.

Here i will use Angular 4 HttpClient and RxJS Observable Api to get data from API service.

  1. student.model.ts – This class is equivalent to java POJO class.
  2. get-student.service.ts – This is Angular service class to call Rest Api.
  3. get-student-info.component.ts – This class is used to call above service class method.
  4. get-student.html – To display student information record.

student.model.ts

export class Student {
   public roll: string;
   public name: string;
}

get-student.service.ts

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

@Injectable()
export class GetStudentInfoService {

  API_URL: string = "api/get/student/info";
  constructor(publichttp:HttpClient) {}
  getStudentInfo():Observable<HttpResponse<Student>> {
        return this.http.get<Student>(
           this.API_URL, { observe:'response' }
        );
  }
}

get-student-info.component.ts

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { GetStudentInfoService } from './get-student.service';
import { Student } from '../customer/student.model';

@Component({
  selector:'get-student-info',
  templateUrl:'./get-student.html'
})
export class GetStudentInfoComponent {
  public student = new Student();
  constructor(private studentInfo: GetStudentInfoService) { }

  ngOnInit() {
      this.showStudntInfomation();
  }

   showStudentInfomation() {
       this.studentInfo.getStudentInfo().subscribe(resp => {
                this.student= { ...resp.body };
                console.log(this.student);
   });
}

}

get-student.html

<table>
<tr>
<td>Roll:</td>
<td>
   <input [(ngModel)]="student.roll"name="roll"readonly>
</td>
</tr>
<tr>
<td>Name:</td>
<td>
    <input [(ngModel)] = "student.name"name="name"readonly>
</td>
</tr>
</table>






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