Angular 5 HttpClient Query Parameters


Angular 5 HttpClient Query Parameters

We can send query parameter value to REST Api using HttpParams in Angular. here in this post i will send student id to Java Rest Api.

Example

  1. get-student.service.ts
  2. get-student-info.component.ts

get-student.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpResponse, HttpParams } from '@angular/common/http';
import { tap } from 'rxjs/operators';

@Injectable()

export class GetStudentInfoService {

   API_URL:string="api/get/student/info";
   constructor(public http: HttpClient) {}
   searchStudent(id:string):Observable<HttpResponse<any>> {
      const options=id?
     { params: new HttpParams().set('id', id) } : {};
     return this.http.get<any>(
     this.API_URL, options).pipe(
     tap(
       data=> (data)
     )
   );
 }
}

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';

@Component({
   selector:'get-student-info',
   templateUrl:'./get-student.html'
 })
export class GetStudentInfoComponent {
   constructor(private studentInfo: GetStudentInfoService) { }
   ngOnInit() {
       this.searchStudent("s-101");
   }
  searchStudent(id:string) {
      this.studentInfo.searchStudent(id).subscribe(response => {
           console.log({ ...response.body });
  });
}

}

 






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