【发布时间】: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