Saturday, 6 July 2019

HTTP Client Angular 6

> Samples
> Angular Samples
> Angular 6 Samples

A DataService has been created to perform the http requests. All services and components will be calling this DataService methods generic methods

data.service.ts

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


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

  baseUrl: string = 'http://localhost:3554/api/';

  retries: number = 0;

  constructor(private httpClient: HttpClient) { }

  //for passing the params check the following thread, accepted answer
  //https://stackoverflow.com/questions/51885155/httpparams-use-with-put-and-post-change-return-type-to-observablehttpeventt/51889413?noredirect=1#comment90730527_51889413

  /**
   * A GET method
   * @param url api url without the leading baseUrl part
   * @param params pass empty meaning do not pass when not used, will cover stuff like ?x=1&y=2,
   *        instead use HttpParams  pass as { params: { sessionTimeOut: 'y' } } or
   *          const params = new HttpParams().set('id', 1).set('name','tahir');
   *        or as following 3 lines
   *        let params = {};
   *        params['params'] = new HttpParams().set('groupType', this.groupType.toString());
   *        params['observe'] = 'body';
   * @returns returns T string/number/model
   */

  pull(url: string, params = {}): Observable {
    url = `${this.baseUrl}${url}`;
    return this.httpClient
      .get(url, { params })
      .pipe(retry(this.retries));
  }


  /**
   * A POST method
   * @param url api url without the leading baseUrl part
   * @param body model posting
   * @param params pass empty meaning do not pass when not used, will cover stuff like ?x=1&y=2,
   *        let params = {};
   *        params['params'] = new HttpParams().set('groupType', this.groupType.toString());
   *        params['observe'] = 'body';
   * @returns returns T string/number/model
   */

  create(url: string, body, params = {}): Observable {
      url = `${this.baseUrl}${url}`;
      //console.log(url);
    return this.httpClient
      .post(url, body, params)
      .pipe(retry(this.retries));
  }


  /**
   * A PUT method
   * @param url api url without the leading baseUrl part
   * @param body model posting
   * @param params pass empty meaning do not pass when not used, will cover stuff like ?x=1&y=2,
   *        let params = {};
   *        params['params'] = new HttpParams().set('groupType', this.groupType.toString());
   *        params['observe'] = 'body';
   * @returns returns T string/number/model
   */

  update(url: string, body, params = {}): Observable {
    url = `${this.baseUrl}/${url}`;
    return this.httpClient
      .put(url, body, params)
      .pipe(retry(this.retries));
  }


  /**
   * A DELETE method
   * @param url api url without the leading baseUrl part
   * @param params pass empty meaning do not pass when not used, will cover stuff like ?x=1&y=2,
   *        let params = {};
   *        params['params'] = new HttpParams().set('groupType', this.groupType.toString());
   *        params['observe'] = 'body';
   */

  remove(url: string, params = {}): Observable {
    url = `${this.baseUrl}${url}`;
    return this.httpClient
      .delete(url, params)
      .pipe(retry(this.retries));
  }


Use of data service

add the data service to app.modules.ts

import { DataService } from './resources/services/data.service';
providers: [DataService]

add the HttpClientModule module

import { HttpClientModule } from '@angular/common/http';
imports: [
    CommonModule,
    HttpClientModule,
  ]


And then in your other service or component, use the above DataService.

constructor(private dataService: DataService) { }

this.projectsSubscription = this.dataService.pull('controller/action').subscribe(
      res => {
        console.log(res);
      },
      error => {
        console.log(error);
      }
    );