角度6-比较两个可观察长度

时间:2018-08-20 14:13:40

标签: javascript angular typescript angular6 angular2-observables

有没有办法比较两个可观测物体的当前长度?

编辑:这是将数组与可观察对象进行比较。 我想将所有元素数与它们进行比较(请参见下面的示例)。

在我尝试执行此操作时,它们已经完全加载。不等待任何数据。

例如,我想做

if (array1.length < array2.length) {
    array1.foreach(item => item.isSelected = true);

我尝试使用管道,地图,点击,但一段时间后它们会解决,对我不起作用。我知道这可能是令人讨厌的概念的突破,但是想知道是否有选择的办法?

2 个答案:

答案 0 :(得分:2)

在另一个Observable中使用解析后的值。

ob1 = of([1,2,3])
ob2 = of([1,2,3, 4]);


  foo() {
  this.ob1.pipe(
    switchMap((data1)=> {
      return this.ob2.pipe(
        map((data2) => {
          console.log(data1, data2); // will print [1,2,3] [1,2,3,4],
                                     //  which now you can compare easily
        })
      )
    })
  ).subscribe();
}

https://stackblitz.com/edit/angular-jmgdyk?file=src%2Fapp%2Fapp.component.ts

答案 1 :(得分:1)

比较长度的一种可能方法是使用zip运算符,如下所示:

import { of } from 'rxjs';
import {  zip } from 'rxjs';

const data = of([20, 21, 30, 40]);
const data1 = of([22, 25, 35, 45]);

const example = zip(data, data1);
example.subscribe(val => console.log(val[0].length, val[1].length));