Skip to content

Instantly share code, notes, and snippets.

@michaelchadwick
Created May 10, 2017 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelchadwick/10eecd58ac4aa38f87c5b7576f9543f2 to your computer and use it in GitHub Desktop.
Save michaelchadwick/10eecd58ac4aa38f87c5b7576f9543f2 to your computer and use it in GitHub Desktop.
async service
// 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