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");
  }

}


Post a Comment

1 Comments

  1. Jackpot Party Casino - Bonuses, FAQs, FAQs - ChoGraX
    Jackpot Party Casino bonus codes, FAQs and other information about 우리카지노 Jackpot Party Casino, 온카지노 including 바카라 검증 사이트 current หาเงินออนไลน์ bonus codes, games, 드림 카지노

    ReplyDelete