Thursday, 25 January 2018

How to Create Common API SERVICE File in Angualr 2

import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { Headers, Http, Response, URLSearchParams, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx'
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';


@Injectable()
export class ApiService {
  constructor(
    private http: Http,
    private jwtService: JwtService
  ) { }

  private setHeaders(): Headers {
    const headersConfig = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };
    if (this.jwtService.getToken()) {
      headersConfig['Authorization'] = `${this.jwtService.getToken()}`;
      if (sessionStorage.getItem("CurrentUserName") != null) {
        headersConfig['AuthorizationID'] = JSON.parse(sessionStorage.getItem("CurrentUserName"))['User_ID'];
      } else { headersConfig['AuthorizationID'] = "Error" }
    }
    return new Headers(headersConfig);
  }

  private formatErrors(error: any) {
    return Observable.throw(error.json());
  }

  get(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> {
    return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), search: params })
      .catch(this.formatErrors)
      .map((res: Response) => res.json());
  }

  put(path: string, body: Object = {}): Observable<any> {
    const options = new RequestOptions({ headers: this.setHeaders() });
    return this.http.put(
      `${environment.api_url}${path}`,
      JSON.stringify(body),
      options
    )
      .catch(this.formatErrors)
      .map((res: Response) => res.json());
  }

  post(path: string, body: Object = {}): Observable<any> {

    const options = new RequestOptions({ headers: this.setHeaders() });
    return this.http.post(
      `${environment.api_url}${path}`,
      JSON.stringify(body),
      options
    )
      .catch(this.formatErrors)
      .map((res: Response) => {
        if (res.json().ReturnMsg === "TOKEN NUMBER NOT MATCH....!!!") {
          this.jwtService.destroyToken()
        }
        return res.json()
      });
  }
  postFile(path: string, body): Observable<any> {
    return this.http.post(`${environment.api_url}${path}`, body)
      .map((res: Response) => {
        if (res.json().ReturnMsg === "TOKEN NUMBER NOT MATCH....!!!") {
          this.jwtService.destroyToken()
        }
        return res.json()
      });
  }

  delete(path): Observable<any> {
    return this.http.delete(
      `${environment.api_url}${path}`,
      { headers: this.setHeaders() }
    )
      .catch(this.formatErrors)
      .map((res: Response) => res.json());
  }
}

******************************************************
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class JwtService {
  constructor(
    private router: Router
  ) { }
  getToken(): String {
    return sessionStorage.getItem('jwtToken');
  }

  saveToken(token: String) {
    sessionStorage.setItem('jwtToken', token.toString());
  }

  destroyToken() {
    window.localStorage.removeItem('jwtToken');
    sessionStorage.removeItem('CurrentUserName');
    sessionStorage.removeItem("HomePageAccess")
    this.router.navigateByUrl("Login");
  }

}


No comments:

Post a Comment

Row based styling for Primeng DataTable using Angualr 2,4

------------------------------------Component.Html---------------- < p -dataTable id = "Tbl" [ rowStyleClass ]= " Fu...