Skip to content

Instantly share code, notes, and snippets.

@danielnv18
Created September 3, 2017 04:43
Show Gist options
  • Save danielnv18/72ee034076605057c7529e32b263954f to your computer and use it in GitHub Desktop.
Save danielnv18/72ee034076605057c7529e32b263954f to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { Request, Http, RequestMethod, RequestOptions, URLSearchParams, Headers } from '@angular/http';
import { ENV } from '../environment/environment';
import 'rxjs/add/operator/map';
@Injectable()
export class Api {
url: string = ENV.API_URL;
constructor(public http: Http) { }
get(endpoint: string, params?: any, options?: RequestOptions) {
return this.request(endpoint, RequestMethod.Get, null, params, options);
}
post(endpoint: string, body: any, params?: any, options?: RequestOptions) {
return this.request(endpoint, RequestMethod.Post, body, params, options);
}
update(endpoint: string, body: any, params?: any, options?: RequestOptions) {
return this.request(endpoint, RequestMethod.Put, body, params, options);
}
delete(endpoint: string, body: any, params?: any, options?: RequestOptions) {
return this.request(endpoint, RequestMethod.Delete, body, params, options);
}
private request(endpoint: string, method: RequestMethod, body?: any, params?: any, options?: RequestOptions) {
if (!options) {
options = new RequestOptions();
}
// Request method
options.method = method;
// URL.
options.url = `${this.url}/${endpoint}`;
if (body) {
options.body = body;
}
// Support easy query params for GET requests
if (params) {
let p = new URLSearchParams();
for (let k in params) {
p.set(k, params[k]);
}
// Set the search field if we have params and don't already have
// a search field set in options.
options.search = !options.search && p || options.search;
}
// Set headers
options.headers = this.setHeaders(options);
let request = new Request(options);
return this.http.request(request).map(res => res.json());
}
private setHeaders(options?: RequestOptions): Headers {
let headers: Headers;
if (!options.headers) {
headers = new Headers();
}
else {
headers = options.headers
}
// Set the Content type header if it isn't already set.
if (!headers.has('Content-type')) {
headers.set('Content-type','application/vnd.api+json')
}
return headers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment