-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.service.ts
55 lines (47 loc) · 1.81 KB
/
api.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { Injectable } from '@angular/core';
import { Headers, Http, URLSearchParams } from '@angular/http';
import { AppConfig } from '../config/app.config';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class ApiService {
private apiBase = new AppConfig().apiBase;
private headers = new Headers({ 'Content-Type': 'application/json' });
constructor(private http: Http) { }
//for all GET operations
get(module: string, parameter?: URLSearchParams): Promise<any> {
return this.http
.get(this.apiBase + module, { search: parameter, headers: this.headers })
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
//for all POST operations
create(module: string, parameter: any): Promise<any> {
return this.http
.post(this.apiBase + module, JSON.stringify(parameter), this.headers)
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
//for all UPDATE operations
update(module: string, parameter: any): Promise<any> {
return this.http
.put(this.apiBase + module + parameter, this.headers)
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
//for all DELETE operations
delete(module: string, parameter: any): Promise<void> {
return this.http.delete(this.apiBase + module + parameter, this.headers)
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
//for error handling
private handleError(error: any): Promise<any> {
console.error('An error occurred : ', error);
return Promise.reject(error.message || error);
}
}