首页 > 解决方案 > 在函数完成使用 Angular 和 Ionic 之前,Promise 已成功解决

问题描述

我创建了一个服务,该服务具有从 API 检索令牌的方法,该 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();
  });  
}

标签: angulartypescriptionic4es6-promiseangular-promise

解决方案


问题是您的函数在异步调用中logIn设置了值,因此当您尚未分配它时。你要早点回来。如果你想使用Promise方法,那么必须返回一个Promisethis.tokenthis.http.postreturn this.token;logIn

async logIn() {
  if(!this.token) {  
    return this.http.post(this.apiURL + "/token/", {username: "test", password: "test"}, options)
      .toPromise()
      .then(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; // important to return the token here
        }
      }
  }
  return this.token;
}

请注意,我已将async关键字添加到logIn函数中,更改了subscribefor toPromise,链接.then并添加return this.token到其中。

希望能帮助到你。


推荐阅读