Angular 2 Http Service

02-22-2017
posts

Our modern applications can do a lot on their own, the power of the client is impressive. But often we need to interact with an API service to have access to our data. Angular 2’s http module simplifies making ajax requests from our front-end app to the server.

Often we need to pass additional information with our request, things like request headers, authentication information, etc. And what happens when our API endpoint URL changes, we don’t want that littered throughout our app. Below is a simple http service that can be imported by other services and exposes basic CRUD methods. The verbs: GET, POST, PUT, DELETE are available while headers and authentication are taken care of by this simple service.

import { Injectable } from '@angular/core';
import { Http, Headers, ResponseContentType } from '@angular/http';

/**
* HttpService - Use to make authorized requests to the API,
* operates as an interceptor, adding headers, etc.
*/

@Injectable()
export class HttpService {

  private apiUrl = 'http://localhost:3000/api';

  constructor(private http: Http) { }

  createAuthorizationHeader(headers: Headers) {

    let token = this.getAuthToken();

    headers.append('Accept', 'application/json');
    headers.append('Authorization', 'Bearer ' + token);
    headers.append('Content-Type', 'application/json');

    return false;
  }

  delete(url, body) {
    let headers = new Headers();
    let token = this.getAuthToken();

    headers.append('Authorization', 'Bearer ' + token);

    return this.http.delete(this.apiUrl + url, {
      headers: headers,
      body: body
    });
  }

  get(url) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);

    return this.http.get(this.apiUrl + url, {
      headers: headers
    });
  }

  getPublic(url) {

    return this.http.get(this.apiUrl + url);

  }

  getAuthToken() {
    let token = sessionStorage.getItem(JSON.parse('authToken'));
    if (token) {
      return token;
    }
    return false;
  }

  post(url, data) {

    let headers = new Headers();
    this.createAuthorizationHeader(headers);

    return this.http.post(this.apiUrl + url, data, {
      headers: headers
    });
  }

  postBlob(url, data) {
    this.createAuthorizationHeader(headers);

    return this.http.post(this.apiUrl + url, data, {
      responseType: ResponseContentType.Blob, headers: headers
    });
  }

  put(url, data) {

    let headers = new Headers();

    this.createAuthorizationHeader(headers);

    return this.http.put(this.apiUrl + url, data, {
      headers: headers
    });
  }

}