【发布时间】:2020-08-22 05:29:49
【问题描述】:
我的服务有问题,我需要异步调用函数 getToken() 以便它初始化 token 和 token_type 变量,这些是能够向 API 发出所有请求所必需的
这是我的服务
async ngOnInit(){
await this.getToken();
}
token: string;
tokenType: string;
getQuery(query: string): Observable<any> {
const url = `https://api.spotify.com/v1/${ query }`;
let bearer = this.tokenType+' '+this.token;
let headers = new HttpHeaders();
headers = headers.set('Authorization', bearer);
console.log(headers);
return this._http.get(url, { headers });
}
getNewReleases() : Observable<any>{
return this.getQuery('browse/new-releases?limit=20')
.pipe( map( data => data['albums'].items ));
}
async getToken(): Promise<any>{
const clientSecret = '764b7c0645b849fa10f50f2a3450028';
const clientId = '567b16bdfd23413294483002be41bc0';
const url = 'http://127.0.0.1:3000/spotify/';
let prom = await this._http.get(url + `${clientId}/${clientSecret}`).toPromise().then((data:any)=>{
this.token = data.access_token;
this.tokenType = data.token_type;
})
}
}
这是我的组件
async ngOnInit() {
await this.spotifyService.getNewReleases().subscribe((data:any)=>{
console.log("comp"+data);
this.newSongs= data;
this.loading=false;
},(err:any)=>{
console.log("error component");
this.error=true;
this.loading=false;
this.errorMsg = err.error.error.message;
});
}
}
【问题讨论】:
标签: angular typescript