-
-
Save pmcfernandes/9b6838a5f23500175d5b51d09092bbbb to your computer and use it in GitHub Desktop.
SIMPLE AND EASY HTTP REQUESTS IN ANGULAR2! GET A PROMISE AND USE IT EASILY!
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
import { Injectable } from '@angular/core'; | |
import { Http } from '@angular/http'; | |
import { Config } from '../Config'; | |
import { Observable } from 'rxjs/Observable'; | |
import 'rxjs/Rx'; | |
@Injectable() | |
export class Request { | |
constructor(public http: Http) | |
{ | |
} | |
get(url): Promise<any> | |
{ | |
return this.http.get(Config.baseUrl + url).map(response => { | |
return response.json() || {success: false, message: "No response from server"}; | |
}).catch((error: Response | any) => { | |
return Observable.throw(error.json()); | |
}).toPromise(); | |
} | |
post(url, data): Promise<any> | |
{ | |
return this.http.post(Config.baseUrl + url, data).map(response => { | |
return response.json() || {success: false, message: "No response from server"}; | |
}).catch((error: Response | any) => { | |
return Observable.throw(error.json()); | |
}).toPromise(); | |
} | |
} |
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
import { Request } from "./Request"; | |
authenticate() | |
{ | |
this.request.get("/user").then(response => { | |
console.log("Got response:", response); | |
}).catch(error => { | |
console.log("Got error:", error); | |
}).then(response => { | |
console.log("Another response:", response); | |
}).catch(error => { | |
console.log("Got another error:", error); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment