Created
May 5, 2017 19:58
-
-
Save rvlb/c692f0183c205e55517e68be5f0e94a5 to your computer and use it in GitHub Desktop.
A simple TypeScript REST API Service implementation (GET & POST)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { Headers, Http, RequestOptions } from '@angular/http'; | |
import 'rxjs/add/operator/toPromise'; | |
@Injectable() | |
export class NewService { | |
constructor(private http: Http) {} | |
getData(url: string): Promise<Object[]> { | |
return this.http.get(url) | |
.toPromise() | |
.then(response => response.json() as Object[]) | |
.catch(this.handleError); | |
} | |
postData(url: string, data: any): Promise<Object> { | |
let headers = new Headers({ 'Content-Type': 'application/json' }); | |
let options = new RequestOptions({ headers: headers }); | |
return this.http.post(url, data, headers) | |
.toPromise() | |
.then(response => response.json()) | |
.catch(this.handleError); | |
} | |
private handleError(error: any): Promise<any> { | |
console.error('An error occurred', error); | |
return Promise.reject(error.message || error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment