Angular 2 - How do I write a Http get promise?
I'm importing http and want to set the http header with my auth token. Then I want to write a http get and put the response into a promise to return to the method that calls it.
So far I have this:
import {Http, Headers} from "angular2/http";
import {EnvironmentService} from './environmentService';
export class AuthService {
private environmentService: EnvironmentService;
private http: Http;
private header: Headers;
contructor(_environmentService: EnvironmentService, _http: Http, _header: Headers){
this.environmentService = _environmentService;
this.http = _http;
this.header.append('Authorization', '1234');
this.header.append('Content-Type', 'application/json');
}
getSpotifyData = ():Promise<Object> => {
return this.http
.get('http://ws.spotify.com/search/1/track.json?q=foo', {headers:this.header})
.map((response) => {
return response.json()
})
.toPromise();
}
}
Thanks in advance!
How To Create Promises in Angular? To create a promise in Angular we just need to use 'new Promise(function)' syntax. The promise constructor takes function as a parameter and that inner function takes resolve and reject as a params.
There are two ways by which we can add the headers. One, we add the HTTP Headers while making a request. The second way is to use the HTTP interceptor to intercept all the Requests and add the Headers. In both cases, we use the httpHeaders configuration option provided by angular HttpClient to add the headers.
Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time. Emit a single value at a time. Are lazy: they're not executed until we subscribe to them using the subscribe() method.
You can pass headers
into the second argument of http.get
method and you can use .toPromise
method to convert an Observable
into a Promise
.
export class AuthService {
// ...
testApiCall(): any {
return this.http
.get('http://localhost:3333/api/', {
headers: {
'Authorization': 'BearerTokenGoesHear'
}
})
.map((response) => {
// some response manipulation
return response.json()
})
.toPromise();
}
}
Take a look at this example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With