Angular 2-如何编写Http得到承诺?
我正在导入http,并希望使用我的auth令牌设置http标头。然后,我想编写一个http get并将响应放入承诺中以返回到调用它的方法。
到目前为止,我有这个:
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();
}
}
提前致谢!
您可以传入methodheaders
的第二个参数,http.get
并且可以使用.toPromise
method将转换Observable
为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();
}
}
看一下这个例子。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句