将最新数据与可观察数组结合起来

发布于 2025-01-11 22:04:14 字数 626 浏览 5 评论 0原文

如何将 combineLatest 与两个或多个可观察数组一起使用?

const array1 = [of(1), of(2)];
const array2 = [of(3), of(4)];

combineLatest(array1, array2)
  .subscribe(([array1, array2]) => {
    console.log(
      `array1[0]: ${array1[0]}
      array1[1]: ${array1[1]}
      array2[0]: ${array2[0]}
      array2[1]: ${array2[1]}`
    );
  });

我有一个堆栈闪电战: https://stackblitz.com/edit/typescript-cnzvlo? file=index.ts&devtoolsheight=100

How would one go about using combineLatest with two or more arrays of observables?

const array1 = [of(1), of(2)];
const array2 = [of(3), of(4)];

combineLatest(array1, array2)
  .subscribe(([array1, array2]) => {
    console.log(
      `array1[0]: ${array1[0]}
      array1[1]: ${array1[1]}
      array2[0]: ${array2[0]}
      array2[1]: ${array2[1]}`
    );
  });

I have a stackblitz:
https://stackblitz.com/edit/typescript-cnzvlo?file=index.ts&devtoolsheight=100

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伪心 2025-01-18 22:04:14

combineLatest 函数需要一个 Observable 数组,而不是 Observable 数组的数组。

因此,您需要做的是:

  • 通过组合每个 Observable 的内部 Observable 数组,将每个 Observable 数组转换为 Observable其中之一使用 concat 函数。
  • 然后使用 toArray 运算符将每个结果转换为数组。

您可以执行如下操作:

import { combineLatest, of, concat } from 'rxjs';
import { toArray } from 'rxjs/operators';

const array1 = [of(1), of(2)];
const array2 = [of(3), of(4)];

combineLatest([
  concat(...array1).pipe(toArray()),
  concat(...array2).pipe(toArray()),
]).subscribe(([array1, array2]) => {
  console.log(
    `array1[0]: ${array1[0]}
      array1[1]: ${array1[1]}
      array2[0]: ${array2[0]}
      array2[1]: ${array2[1]}`
  );
});

这是 StackBlitz 的工作版本:
https://stackblitz.com/edit/typescript-3imea6?file=index.html ts

The combineLatest function expects an array of Observable(s), not an array of array of Observable.

So what do you have to do is:

  • Convert each array of Observable, to an Observable, by combining the inner Observable(s) of each one of them using concat function.
  • Then convert the result of each one to an array using toArray operator.

You can do something like the following:

import { combineLatest, of, concat } from 'rxjs';
import { toArray } from 'rxjs/operators';

const array1 = [of(1), of(2)];
const array2 = [of(3), of(4)];

combineLatest([
  concat(...array1).pipe(toArray()),
  concat(...array2).pipe(toArray()),
]).subscribe(([array1, array2]) => {
  console.log(
    `array1[0]: ${array1[0]}
      array1[1]: ${array1[1]}
      array2[0]: ${array2[0]}
      array2[1]: ${array2[1]}`
  );
});

And here is the working version of your StackBlitz:
https://stackblitz.com/edit/typescript-3imea6?file=index.ts

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文