Angular 2 - 如何在标题中编写Http get promise? [英] Angular 2 - How do I write a Http get promise in my header?
本文介绍了Angular 2 - 如何在标题中编写Http get promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Angular 2 - 如何编写Http get promise?
Angular 2 - How do I write a Http get promise?
我正在导入http并希望使用我的身份验证令牌设置http标头。
然后我想编写一个http get并将响应放入一个承诺,返回调用它的方法。
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.
到目前为止我有这个:
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();
}
}
提前致谢!
推荐答案
您可以传递 headers
进入 http.get
方法,您可以使用 .toPromise
方法将 Observable
转换为 Promise
。
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();
}
}
看看这个例子。
这篇关于Angular 2 - 如何在标题中编写Http get promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文