2016-03-14 20:20:29 +08:00
|
|
|
///<reference path="../../browser.d.ts"/>
|
2016-03-13 05:19:24 +08:00
|
|
|
|
2016-03-19 16:58:27 +08:00
|
|
|
import {Http, Headers, RequestOptions, Response} from "angular2/http";
|
2016-03-13 18:28:29 +08:00
|
|
|
import {Message} from "../../../common/entities/Message";
|
2016-03-19 16:58:27 +08:00
|
|
|
import "rxjs/Rx";
|
2016-03-13 05:19:24 +08:00
|
|
|
|
2016-03-13 18:28:29 +08:00
|
|
|
export class NetworkService{
|
2016-03-13 05:19:24 +08:00
|
|
|
|
2016-03-19 16:58:27 +08:00
|
|
|
_baseUrl = "/api";
|
2016-03-13 05:19:24 +08:00
|
|
|
|
2016-03-19 16:58:27 +08:00
|
|
|
constructor(protected _http:Http){
|
2016-03-13 05:19:24 +08:00
|
|
|
}
|
|
|
|
|
2016-03-20 00:31:42 +08:00
|
|
|
private callJson(method:string, url:string, data:any = {}){
|
2016-03-19 16:58:27 +08:00
|
|
|
let body = JSON.stringify({ data });
|
|
|
|
let headers = new Headers({ 'Content-Type': 'application/json' });
|
|
|
|
let options = new RequestOptions({ headers: headers });
|
|
|
|
console.log(this._http.post(this._baseUrl+url, body, options));
|
2016-03-20 02:59:19 +08:00
|
|
|
return this._http[method](this._baseUrl+url, body, options)
|
2016-03-19 16:58:27 +08:00
|
|
|
.toPromise()
|
|
|
|
.then(res => <Message<any>> res.json())
|
|
|
|
.catch(NetworkService.handleError);
|
2016-03-13 18:28:29 +08:00
|
|
|
}
|
|
|
|
|
2016-03-20 00:31:42 +08:00
|
|
|
protected postJson(url:string, data:any = {}){
|
|
|
|
return this.callJson("post",url,data);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected putJson(url:string, data:any = {}){
|
|
|
|
return this.callJson("put",url,data);
|
|
|
|
}
|
|
|
|
protected getJson(url:string, data:any = {}){
|
|
|
|
return this.callJson("get",url,data);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected updateJson(url:string, data:any = {}){
|
|
|
|
return this.callJson("update",url,data);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected deleteJson(url:string, data:any = {}){
|
|
|
|
return this.callJson("delete",url,data);
|
|
|
|
}
|
|
|
|
|
2016-03-19 16:58:27 +08:00
|
|
|
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-13 05:19:24 +08:00
|
|
|
}
|
|
|
|
}
|