Last active
March 27, 2019 12:35
-
-
Save azarus/c9b0936f51bcc8ed99ffde96b90eaf24 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); | |
}); | |
} |
I think reading the code makes sense no?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much been looknig for something like this for a while.