订阅RxJS中的Promise后的未定义变量

时间:2020-11-03 12:40:35

标签: angular promise rxjs angular-components

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

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

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的值保持未定义的事件?

1 个答案:

答案 0 :(得分:0)

如果您想使用.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函数设置了属性之后,然后将其打印到控制台。