Ok, first create
1. Util.ts file --
import * as pe from 'parse-error';
import { environment } from '../../environments/environment';
export class Util {
static async post(url, data, isFormData?: any) {
var headers = new Headers();
if (url[0] == '/'){
url = this.getApiUrl() + url;
headers = this.apiHeaders(headers, isFormData);
}
let err, res;
[err, res] = await this.to(this.http.post(url, data, { headers: headers }).toPromise(), false);
return this.responder(err, res);
}
static to(promise, parse?) {// global function that will help use handle promise rejections, this article talks about it http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/
return promise.then(data => {
return [null, data];
}).catch(err => {
if (parse === false) return [err];
return [pe(err)]
});
}
static getApiUrl(){
return environment.apiUrl;
}
static apiHeaders(headers: any, isFormData?: any) {
if (isFormData !== undefined) {
headers.append('mimeType', 'multipart/form-data');
} else {
headers.append('Content-Type', 'application/json');
}
let user:User = <User> User.Auth();
if (user){
let token: string = user.token;
headers.append('Authorization', token);
}
return headers;
}
static responder(err, res){
let send;
if (err) send = err;
if (res) send = res;
return JSON.parse(send._body);
}
}
1. Update environment file --
<code>
export const environment = {
production: false,
apiUrl: 'http://localhost:8080'
};
</code>
2. Update your Component -
<code>
import { Util } from './../helpers/util.helper';
static async getBuLevelResult(startDate, endDate, otherData?: any) {
let err, res; // get from API
const u_id = this.getlocalStorage('User');
let dataSet: any;
dataSet = {
'startDate': startDate + ' 00:00:00',
'endDate': endDate + ' 23:59:00'
};
if (otherData) {
dataSet.projectId = otherData.projectId;
}
[err, res] = await Util.to(Util.post('/selfService/user/' + u_id[0].userId + '/dashboard/piechart/getBuLevelData', dataSet));
if (err) {
Util.TE(err.message, true);
} else {
return res.data;
}
}
</code>