【问题标题】:Subscription to Observable is happening too late in the function to access data在函数中订阅 Observable 为时已晚,无法访问数据
【发布时间】:2020-12-02 09:18:36
【问题描述】:

我正在尝试订阅 Observable 并将其存储在变量中

      this.waiverData = this.waiverService
        .searchForWaiver(this.waiverTypeId, this.policyNumber, this.dateOfLoss)
        .subscribe(data => {
          this.waiverData = data;

这工作到一定程度,但通话停止

    .subscribe(data => {

并直接跳转到 if 语句而不从对象中捕获数据。然后它运行 if 语句,一旦检查了所有条件,它就会跳回到订阅处

    this.waiverData = data;

然后返回包含我需要且可访问的所有数据的完整对象。这发生得太晚了.. 这是完整的功能:

    standardWaiver: StandardWaiver = new StandardWaiver();
    // standardWaiver: StandardWaiver;
    // standardWaiver: any;
    dateOfLoss: Date = null;
    waiverData: any;

async  searchForDuplicateAndCAP() { 
    // the search for duplicate function will call the search for waiver in cap function
    if (this.waiverTypeId === 1)
    {
    this.waiverData = this.waiverService
    .searchForWaiver(this.waiverTypeId, this.policyNumber, this.dateOfLoss)
    .subscribe(data => {
      this.waiverData = data;
      }
     );

      if (this.waiverData.duplicateFound === true) {
        // console.log(this.duplicateFound, + 'if duplicate found')
        this.showIfWaiverExistsInXXXXX = true;
        this.showIfWaiverDataNotFoundInXXXXX = false;
      } 
      else if (stuff){
     }
      else {
}

您是否知道如何在 if 语句之前完成调用或为什么不完成。先感谢您。 这是一个更新的问题

【问题讨论】:

  • 尝试删除 this.waiverData = this.waiverService... 分配?这似乎没有必要,只需运行没有它的方法this.waiverService.searchForWaiver...
  • 谢谢@Houang Dao... 我需要this.waiverData 来订阅另一个函数的Observable。它工作正常,但我在调用订阅之前跳出订阅并进入 if 语句。

标签: node.js angular typescript


【解决方案1】:

我找到了访问可变数据源的解决方案。您必须在订阅中运行函数/方法才能立即访问数据。

这里是解决方案的链接:

https://stackoverflow.com/a/52081230/9183130

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    相关资源
    最近更新 更多