Angular 2 - 如何在 header 中编写 Http get promise?
Angular 2 - How do I write a Http get promise in my header?
Angular 2 - 如何编写 Http get promise?
我正在导入 http 并希望使用我的身份验证令牌设置 http header。
然后我想写一个http get并将响应放入对return调用它的方法的承诺中。
到目前为止我有这个:
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
into the second argument of http.get
method and you can use .toPromise
方法将 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();
}
}
看看this example。
Angular 2 - 如何编写 Http get promise?
我正在导入 http 并希望使用我的身份验证令牌设置 http header。 然后我想写一个http get并将响应放入对return调用它的方法的承诺中。
到目前为止我有这个:
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
into the second argument of http.get
method and you can use .toPromise
方法将 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();
}
}
看看this example。