1
0
mirror of https://github.com/bpatrik/pigallery2.git synced 2025-01-04 03:49:28 +02:00
pigallery2/frontend/app/model/network/network.service.ts

56 lines
1.8 KiB
TypeScript
Raw Normal View History

///<reference path="../../../browser.d.ts"/>
2016-03-12 23:19:24 +02:00
import {Http, Headers, RequestOptions, Response} from "angular2/http";
import {Message} from "../../../../common/entities/Message";
import "rxjs/Rx";
import {Utils} from "../../../../common/Utils";
2016-03-12 23:19:24 +02:00
2016-03-13 12:28:29 +02:00
export class NetworkService{
2016-03-12 23:19:24 +02:00
_baseUrl = "/api";
2016-03-12 23:19:24 +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 );
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
2016-03-20 17:54:30 +02:00
if(method == "get"){
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)
.toPromise()
.then(res => <Message<any>> res.json())
.catch(NetworkService.handleError);
2016-03-13 12:28:29 +02:00
}
2016-03-20 17:54:30 +02:00
protected postJson<T>(url:string, data:any = {}): Promise<T>{
return this.callJson("post",url,data);
}
2016-03-20 17:54:30 +02:00
protected putJson<T>(url:string, data:any = {}): Promise<T>{
return this.callJson("put",url,data);
}
2016-03-20 17:54:30 +02:00
protected getJson<T>(url:string): Promise<T>{
return this.callJson("get",url);
}
2016-03-20 17:54:30 +02:00
protected deleteJson<T>(url:string, data:any = {}): Promise<T>{
return this.callJson("delete",url,data);
}
private static handleError (error: any) {
// in a real world app, we may send the error to some remote logging infrastructure
// 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
}
}