简体   繁体   English

Angular 如何用 Observables 链接函数

[英]Angular how to chain functions with Observables

I have datatables, and I would like to fill them by subscribing to Observables.我有数据表,我想通过订阅 Observables 来填充它们。 When I load the page, I get an error, because the data (financeProducts) is not yet defined when I would like access its ".cancelled" property.当我加载页面时,我得到一个错误,因为当我想访问它的“.cancelled”属性时数据(financeProducts)尚未定义。 How can I improve my code so that I get all the necessary data for the functions?如何改进我的代码,以便获得函数的所有必要数据?

What I have tried:我试过的:

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);
    };
  }

Put the code where you are getting the undefined error inside the subscribe.将代码放在订阅中出现undefined错误的位置。

as @Kokogino mentioned, another enhancement you can do is substitute map with tap since you are not transforming the data, just assigning!正如@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