【问题标题】:Undefined variables after subscribing for a promise in RxJS在 RxJS 中订阅 promise 后未定义的变量
【发布时间】:2021-02-16 03:25:48
【问题描述】:

我正在尝试使用 RxJS 承诺更新 Angular 中的组件变量,并使用函数 .then() 更新本地组件属性,但执行后,组件属性的值保持未定义,为什么?

我正在尝试像这样更新组件的属性:

beautiful-layout.component.ts

myComponentProperty: string;

logMyBeautifulMessage() {
  myPromiseFunction();
  console.log(this.myComponentProperty);
  // At this point, myComponentProperty keeps undefined.
}

myPromiseFunction() {
  this.myHttpService.findAll().toPromise().then(response => {
      this.myComponentProperty = response.helloMessage;
      console.log(this.myComponentProperty);
      // At this point, myComponentProperty has the value of 'Hello World!' as it should be.
    }
  );
}

为什么myComponentProperty的值在执行等待promise并正确设置属性值的函数后保持未定义事件?

【问题讨论】:

  • 承诺是异步操作。您的错误假设是,该函数等待承诺。 then() 在您将属性登录到logMyBeautifulMessage 后执行。
  • 所以最好使用 async/await 声明而不是使用 then() 函数?
  • 是的,如果你真的想等待,你应该创建异步方法async logMyBeautifulMessage() { this.myComponentProperty = (await this.myHttpService.findAll().toPromise()).helloMessage; console.log(this.myComponentProperty); }
  • 知道了,我认为有任何方法可以使用 then() 函数,但我用 async/await 操作替换它并且工作正常,非常感谢!

标签: angular promise rxjs angular-components


【解决方案1】:

如果您想使用.then() 执行此操作,您可以像这样重做。

myComponentProperty: string;

logMyBeautifulMessage() {
  myPromiseFunction().then(property => 
    console.log(`Updated property: ${property}`)
  );
}

myPromiseFunction() {
  return this.myHttpService.findAll().toPromise().then(response => {
    this.myComponentProperty = response.helloMessage;
    return this.myComponentProperty;
  });
}

这就是说:在我的 promise 函数设置了属性之后,然后将它打印到控制台。

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多