1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2024-11-03 21:04:03 +08:00
pigallery2/frontend/app/model/network/network.service.ts

58 lines
1.8 KiB
TypeScript
Raw Normal View History

///<reference path="../../../browser.d.ts"/>
2016-03-13 05:19:24 +08:00
2016-05-09 23:04:56 +08:00
import {Injectable} from "@angular/core";
2016-05-04 23:20:21 +08:00
import {Http, Headers, RequestOptions} from "@angular/http";
import {Message} from "../../../../common/entities/Message";
2016-05-05 03:08:05 +08:00
import "rxjs/Rx";
2016-03-13 05:19:24 +08:00
2016-05-05 03:08:05 +08:00
@Injectable()
2016-05-09 23:04:56 +08:00
export class NetworkService {
2016-03-13 05:19:24 +08:00
_baseUrl = "/api";
2016-03-13 05:19:24 +08:00
2016-05-09 23:04:56 +08:00
constructor(protected _http:Http) {
2016-03-13 05:19:24 +08:00
}
2016-05-09 23:04:56 +08: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 23:54:30 +08:00
2016-05-09 23:04:56 +08:00
if (method == "get" || method == "delete") {
return this._http[method](this._baseUrl + url, options)
2016-03-20 23:54:30 +08:00
.toPromise()
.then(res => <Message<any>> res.json())
.catch(NetworkService.handleError);
2016-05-16 17:03:11 +08:00
}
2016-05-09 23:04:56 +08:00
return this._http[method](this._baseUrl + url, body, options)
.toPromise()
.then(res => <Message<any>> res.json())
.catch(NetworkService.handleError);
2016-03-13 18:28:29 +08:00
}
2016-05-09 23:04:56 +08:00
public postJson<T>(url:string, data:any = {}):Promise<T> {
return this.callJson("post", url, data);
}
2016-05-09 23:04:56 +08:00
public putJson<T>(url:string, data:any = {}):Promise<T> {
return this.callJson("put", url, data);
}
2016-05-09 23:04:56 +08:00
public getJson<T>(url:string):Promise<T> {
return this.callJson("get", url);
}
2016-05-09 23:04:56 +08:00
public deleteJson<T>(url:string):Promise<T> {
return this.callJson("delete", url);
}
2016-05-09 23:04:56 +08:00
private static handleError(error:any) {
// TODO: 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
}
}