Skip to content

Instantly share code, notes, and snippets.

@figloalds
Last active December 22, 2017 14:37
Show Gist options
  • Save figloalds/c58da32b77f4273b2145e78022248352 to your computer and use it in GitHub Desktop.
Save figloalds/c58da32b77f4273b2145e78022248352 to your computer and use it in GitHub Desktop.
//
// ApiService
// Felype Rennan / 2017
// usage Example:
// try {
// var values = await this.api.get('api/Values');
// } catch(err) {
// // handle some err
// }
import { Injectable } from '@angular/core';
import { Http, Request, Response, RequestOptionsArgs, Headers, BaseRequestOptions, RequestOptions } from '@angular/http'
import { environment } from '../environments/environment';
import 'rxjs/Rx';
import { Router } from '@angular/router';
@Injectable()
export class ApiService {
constructor(private http: Http) {
}
private mapUrl(url: string) {
if(!url.startsWith('/')) {
url = '/' + url;
}
var prodUrl = '';
// TODO: Set Development Base API uri here
var devUrl = 'http://localhost:5000';
var apiUrl = '';
if(environment.production) {
apiUrl = prodUrl;
} else {
apiUrl = devUrl;
}
url = apiUrl + url;
return url;
}
async get(api:string) {
return await this.chamarApi(api, null, 'GET');
}
async post(api:string, postData:any) {
return await this.chamarApi(api, postData, 'POST');
}
private async chamarApi(api:string, postData:Object, method:string) : Promise<any> {
var access_token = localStorage.getItem('access_token');
var options:RequestOptionsArgs = {
url: this.mapUrl(api),
headers: new Headers({
'Authentication': 'bearer '+access_token,
})
};
options.method = method;
if(postData) {
options.body = postData;
} else {
options.body = null;
postData = null;
}
var retv = this.http.request(this.mapUrl(api), options)
.toPromise()
.catch((err) => {
throw JSON.parse(err._body);
})
.then((data:any) => {
return JSON.parse(data._body);
});
return retv;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment