Skip to content

Instantly share code, notes, and snippets.

@rvlb
Created May 5, 2017 19:58
Show Gist options
  • Save rvlb/c692f0183c205e55517e68be5f0e94a5 to your computer and use it in GitHub Desktop.
Save rvlb/c692f0183c205e55517e68be5f0e94a5 to your computer and use it in GitHub Desktop.
A simple TypeScript REST API Service implementation (GET & POST)
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