简体   繁体   中英

Angular how to chain functions with Observables

I have datatables, and I would like to fill them by subscribing to 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. 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.

as @Kokogino mentioned, another enhancement you can do is substitute map with tap since you are not transforming the data, just assigning!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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