Created
May 10, 2017 22:57
-
-
Save michaelchadwick/10eecd58ac4aa38f87c5b7576f9543f2 to your computer and use it in GitHub Desktop.
async service
This file contains hidden or 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
// src/app/service.ts | |
import { Injectable } from '@angular/core'; | |
import { Headers, Http } from '@angular/http'; | |
import 'rxjs/add/operator/toPromise'; | |
@Injectable() | |
export class MyService { | |
private headers = new Headers({'Content-Type': 'application/json'}); | |
private apiUrl = 'http://localhost:8000'; // URL to web api | |
constructor(private http: Http) {} | |
methodA(arg1: number): Promise<any> { | |
if(Number.isInteger(arg1) && arg1 >= 0) { | |
return this.http | |
.get(`${this.apiUrl}/arg1/${arg1}`) | |
.toPromise() | |
.then(response => response.json()) | |
.catch(this.handleError); | |
} else { | |
return this.handleError('error: invalid arg1'); | |
} | |
} | |
handleError(error: any): Promise<any> { | |
console.error('Error returning promise from service', error); | |
return Promise.reject(new Error(error.message || error)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment