Angular 6 - compare two observables lengths

纵然是瞬间 提交于 2021-01-27 07:34:46

问题


Is there a way to compare the current length of two observables?

EDIT: It is to compare the arrays withing the observables. I want to compare all the elements count withing them(See example below).

At the point I am trying to do it, they are already completely loaded. Not waiting on any data.

For example I want to do:

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

I tried using pipe, map, tap, but they resolve after some time and don't work for me. I know this might be a breaking of obserables concepts, but was wondering if there is an option to do it?


回答1:


Use the resolved values of one Observable inside the other.

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




回答2:


A possible way to compare the length is the zip operator as follow:

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


来源:https://stackoverflow.com/questions/51932690/angular-6-compare-two-observables-lengths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!