Angular 6 - 比较两个可观察量的长度
Angular 6 - compare two observables lengths
有没有办法比较两个 observable 的当前长度?
编辑:这是将数组与可观察对象进行比较。
我想比较所有元素的数量(请参见下面的示例)。
在我尝试这样做的时候,它们已经完全加载了。不等待任何数据。
例如我想做的:
if (array1.length < array2.length) {
array1.foreach(item => item.isSelected = true);
我尝试使用 pipe、map、tap,但它们会在一段时间后解决并且对我不起作用。我知道这可能会破坏 obserables 概念,但想知道是否可以选择这样做?
比较长度的一种可能方法是 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));
在另一个中使用一个 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
有没有办法比较两个 observable 的当前长度?
编辑:这是将数组与可观察对象进行比较。 我想比较所有元素的数量(请参见下面的示例)。
在我尝试这样做的时候,它们已经完全加载了。不等待任何数据。
例如我想做的:
if (array1.length < array2.length) {
array1.foreach(item => item.isSelected = true);
我尝试使用 pipe、map、tap,但它们会在一段时间后解决并且对我不起作用。我知道这可能会破坏 obserables 概念,但想知道是否可以选择这样做?
比较长度的一种可能方法是 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));
在另一个中使用一个 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