Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
177
rated 0 times [  183] [ 6]  / answers: 1 / hits: 17368  / 9 Years ago, wed, november 11, 2015, 12:00:00

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!


More From » angular

 Answers
23

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.


[#64438] Monday, November 9, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
draven

Total Points: 641
Total Questions: 101
Total Answers: 110

Location: Nicaragua
Member since Mon, Sep 26, 2022
2 Years ago
;