Last active
September 10, 2018 19:15
-
-
Save danielnaranjo/c41b654088bb5333fbbebb6445dfa944 to your computer and use it in GitHub Desktop.
HTTP calls using a reusable function (TS, Angular 5/6)
This file contains 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 { Component, Injectable } from '@angular/core'; | |
import * as urljoin from 'url-join'; | |
import { environment } from '../environments/environment'; | |
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http'; | |
import { Router } from '@angular/router'; | |
@Injectable() | |
export class DataProvider { | |
apiUrl: string; | |
constructor ( | |
private http: HttpClient, | |
private router: Router | |
) { | |
this.apiUrl = environment.path; | |
} | |
requestPost = (endpoint: any, data: any) => { | |
const body = JSON.stringify(data); | |
return this.http.post( urljoin( this.apiUrl, endpoint ), body, { } ) | |
.toPromise() | |
.then((response: Response) => response) | |
.catch(error => error); | |
} | |
requestGet = (endpoint: any, data: any) => { | |
return this.http.get( urljoin( this.apiUrl, endpoint ), { }) | |
.toPromise() | |
.then((response: Response) => response) | |
.catch(error => error); | |
} | |
} |
This file contains 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
getData () { | |
this.dataProvider.requestGet(`enpoint?x=${this.x}&limit25`, {}) | |
.then( | |
data => { | |
// Using lodash to improve performance and reduce HTTP calls to remote server | |
this.results = unionBy(data.results, 'field'); | |
sessionStorage.setItem('x', JSON.stringify(data['results']) ); | |
this.total = filter( data.counts, [ 'x', 'field'] )[0].count; | |
}, | |
err => { | |
console.log(err) | |
sessionStorage.setItem('x', ''); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment