2016-04-30 18:01:54 +02:00
|
|
|
///<reference path="../../../browser.d.ts"/>
|
2016-03-12 23:19:24 +02:00
|
|
|
|
2016-05-04 21:08:05 +02:00
|
|
|
import {Injectable} from '@angular/core';
|
2016-05-04 17:20:21 +02:00
|
|
|
import {Http, Headers, RequestOptions} from "@angular/http";
|
2016-04-30 18:01:54 +02:00
|
|
|
import {Message} from "../../../../common/entities/Message";
|
2016-05-04 21:08:05 +02:00
|
|
|
import "rxjs/Rx";
|
2016-03-12 23:19:24 +02:00
|
|
|
|
2016-05-04 21:08:05 +02:00
|
|
|
@Injectable()
|
2016-03-13 12:28:29 +02:00
|
|
|
export class NetworkService{
|
2016-03-12 23:19:24 +02:00
|
|
|
|
2016-03-19 10:58:27 +02:00
|
|
|
_baseUrl = "/api";
|
2016-03-12 23:19:24 +02:00
|
|
|
|
2016-03-19 10:58:27 +02:00
|
|
|
constructor(protected _http:Http){
|
2016-03-12 23:19:24 +02:00
|
|
|
}
|
|
|
|
|
2016-03-20 17:54:30 +02:00
|
|
|
private callJson<T>(method:string, url:string, data:any = {}): Promise<T>{
|
|
|
|
let body = JSON.stringify( data );
|
2016-03-19 10:58:27 +02:00
|
|
|
let headers = new Headers({ 'Content-Type': 'application/json' });
|
|
|
|
let options = new RequestOptions({ headers: headers });
|
2016-03-20 17:54:30 +02:00
|
|
|
|
2016-05-03 14:29:24 +02:00
|
|
|
if(method == "get" || method == "delete"){
|
2016-03-20 17:54:30 +02:00
|
|
|
return this._http[method](this._baseUrl+url, options)
|
|
|
|
.toPromise()
|
|
|
|
.then(res => <Message<any>> res.json())
|
|
|
|
.catch(NetworkService.handleError);
|
|
|
|
}
|
|
|
|
|
2016-03-19 20:59:19 +02:00
|
|
|
return this._http[method](this._baseUrl+url, body, options)
|
2016-03-19 10:58:27 +02:00
|
|
|
.toPromise()
|
|
|
|
.then(res => <Message<any>> res.json())
|
|
|
|
.catch(NetworkService.handleError);
|
2016-03-13 12:28:29 +02:00
|
|
|
}
|
|
|
|
|
2016-05-04 21:08:05 +02:00
|
|
|
public postJson<T>(url:string, data:any = {}): Promise<T>{
|
2016-03-19 18:31:42 +02:00
|
|
|
return this.callJson("post",url,data);
|
|
|
|
}
|
|
|
|
|
2016-05-04 21:08:05 +02:00
|
|
|
public putJson<T>(url:string, data:any = {}): Promise<T>{
|
2016-03-19 18:31:42 +02:00
|
|
|
return this.callJson("put",url,data);
|
|
|
|
}
|
2016-05-05 17:51:51 +02:00
|
|
|
|
2016-05-04 21:08:05 +02:00
|
|
|
public getJson<T>(url:string): Promise<T>{
|
2016-03-20 17:54:30 +02:00
|
|
|
return this.callJson("get",url);
|
2016-03-19 18:31:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2016-05-04 21:08:05 +02:00
|
|
|
public deleteJson<T>(url:string): Promise<T>{
|
|
|
|
return this.callJson("delete",url);
|
2016-03-19 18:31:42 +02:00
|
|
|
}
|
|
|
|
|
2016-03-19 10:58:27 +02:00
|
|
|
private static handleError (error: any) {
|
2016-05-05 17:51:51 +02:00
|
|
|
// TODO: in a real world app, we may send the error to some remote logging infrastructure
|
2016-03-19 10:58:27 +02:00
|
|
|
// instead of just logging it to the console
|
|
|
|
console.error(error);
|
|
|
|
return Promise.reject(error.message || error.json().error || 'Server error');
|
2016-03-12 23:19:24 +02:00
|
|
|
}
|
|
|
|
}
|