Skip to content

Instantly share code, notes, and snippets.

@azarus
Last active March 27, 2019 12:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save azarus/c9b0936f51bcc8ed99ffde96b90eaf24 to your computer and use it in GitHub Desktop.
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!
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();
}
}
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);
});
}
@dannythebestguy
Copy link

dannythebestguy commented May 25, 2017

Thank you very much been looknig for something like this for a while.

@azarus
Copy link
Author

azarus commented Jun 5, 2017

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