繁体   English   中英

Angular 如何用 Observables 链接函数

[英]Angular how to chain functions with Observables

我有数据表,我想通过订阅 Observables 来填充它们。 当我加载页面时,我得到一个错误,因为当我想访问它的“.cancelled”属性时数据(financeProducts)尚未定义。 如何改进我的代码,以便获得函数的所有必要数据?

我试过的:

ngOnInit() {
    this.setUpData();
  }

  setUpData() {
    forkJoin([this.financeStatusService.getProducts(), this.accountService.getAccounts()])
      .pipe(
        map(([products, accounts]) => {
            this.financeProducts = products;
            this.accountsList = accounts;
          })
        ).subscribe();
          if (this.financeProducts.cancelled) {
             ...
          } else {
             ...
            this.setFinanceTableRows(this.financeProducts);
          }
  }

  setFinanceTableRows(product) {
    const finRow: FinRowWithID = {
      accountName: product.name,
      ...
      id: this.accountsList.filter(entry => entry.id);
    };
  }

将代码放在订阅中出现undefined错误的位置。

正如@Kokogino 提到的,您可以做的另一项增强是用tap替换map因为您没有转换数据,只是分配!

setUpData() {
    forkJoin([this.financeStatusService.getProducts(), this.accountService.getAccounts()])
      .pipe(
        tap(([products, accounts]) => {
            this.financeProducts = products;
            this.accountsList = accounts;
          })
        ).subscribe(() => {
            if (this.financeProducts.cancelled) {
                        // ...
            } else {
                // ...
                this.setFinanceTableRows(this.financeProducts);
            }
        });
  }

  setFinanceTableRows(product) {
    const finRow: FinRowWithID = {
      accountName: product.name,
      // ...
      id: this.accountsList.filter(entry => entry.id);
    };
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM