【发布时间】:2020-04-24 02:34:05
【问题描述】:
我创建了一个服务,该服务具有从 API 检索令牌的方法,该方法在内部调用 subscribe()。这个方法是从一个组件调用的,它不返回一个 Observable,只是一个包含令牌的字符串。
然后,在获得令牌后,应该从组件中调用另一个方法,但是,它总是在另一个方法之前被调用。我什至尝试过在组件中使用 async/await,但它不起作用。
// api.service.ts
logIn() {
if(!this.token) {
this.http.post(this.apiURL + "/token/", {username: "test", password: "test"}, options).subscribe(response => {
if(response.status == 200) {
this.body = response.body;
this.token = "Token " + this.body.token;
window.sessionStorage.setItem("TOKEN_KEY", this.token);
console.log(this.token);
}
}
return this.token;
}
如您所见,该方法只返回令牌,因此我在组件中创建了一个 Promise,一旦解决了就调用 getProduct() 方法,但它在令牌已经存在之前被调用。
// product.component.ts
async getLogin() {
const resp = await this.apiService.logIn();
console.log(resp);
}
getMenu() {
this.apiService.getMenu().subscribe(resp => {
console.log(resp);
});
constructor(private apiService: APIService) {
this.getLogin().then(resp => {
console.log('Called');
// Call before the token has already been created!
this.getMenu();
});
}
【问题讨论】:
标签: angular typescript ionic4 es6-promise angular-promise