角度-如何在另一个可观察值内部使用一个可观察值的结果?

时间:2020-02-19 11:15:19

标签: angular observable

我有一个可观察对象,我订阅了该对象,并对结果值(reduce()map())进行了一些操作。

但是在该可观察变量中,我想调用另一个仅返回一个数字的可观察变量,并且我需要在我的map()中使用该数字。

这里是一个示例:

this.getYearlyDataByIdAndYear(292, 2019).subscribe(result = > {
        let ferienSaldo: FerienSaldo;
        this.getVacationsYearlyDataByIdAndYear(292, 2019).subscribe(result = > {
            // this is my inner observable and I need to save this result, and use it below!
            ferienSaldo = result;
        });
        this.yearlyOverview = result.reduce < Array < YearlyOverview >> ((prev, current, i, all) = > {
                // some code that is not important
                let overviewVar: YearlyOverview = {
                    saldo: ferienSaldo.value
                };
                prev.push(newTLOverview);
            }
            return prev;
        }, new Array < YearlyOverview > ())
});

基本上可以看到,在我的初始Observable内部,我需要内部的值,然后将其复制到reduce()内部,以将其分配给我正在创建的新对象! / p>

我的代码存在的问题是,“ let ferienSaldo”变量无法在第二个可观察的内部访问,此外,我敢肯定,有更好的方法可以将其组合起来!

1 个答案:

答案 0 :(得分:1)

这两个调用似乎并不相互依赖,因此您可以在forkJoin中并行运行它们

forkJoin([
  this.getYearlyDataByIdAndYear(292, 2019).pipe(
    tap(result => this.result1 = result)
  ),
  this.getVacationsYearlyDataByIdAndYear(292, 2019).pipe(
    tap(result => this.result2 = result)
  )
]).subscribe(() => {
  // process this.result1 and this.result2
  // TODO: more meaningful property names
});

编辑:

我使用水龙头是因为我想保持订阅主体的清洁。您还可以将结果返回到数组中进行订阅:

forkJoin([
  this.getYearlyDataByIdAndYear(292, 2019),
  this.getVacationsYearlyDataByIdAndYear(292, 2019)
]).subscribe(result => {
  // process result[0] and result[1]
});

在这样一个简单的示例中,第二个选项看起来更干净,但是我发现将您的订阅主体与数组索引耦合很烦人-尤其是在进行更改时。

相关问题