构建并执行具有带打字稿和Angular变量的可观察物的动态列表

发布于 2025-02-05 08:31:31 字数 746 浏览 5 评论 0原文

我正在收到一个具有1..n用户ID的数组。我正在构建这些ID的唯一

const uniqueUserIds = [
  ...new Set(requests.map((item) => Number(item.userId))),
];

列表代码块。

var tasks: Observable<User>[] = [];
uniqueUserIds.map((userId) => {
  tasks.push(this.getUserInfo(userId));
});

getUserInfo方法只返回可观察的&lt; user&gt;

getUserInfo(userId: number) {
  return this.userServiceHttpClient.getUser(userId);
}

我已经尝试使用以下内容,但是我的一个可观察到的都没有执行:

Promise.all(tasks).then((value) => {
  console.warn(value);
});

如果我采用该值并执行<<<<代码> .subscribe ,然后执行可观察到的。是否有一种方法可以列出可观察到的列表,所有返回相同类型,将结果串入数组,然后继续执行?

I am receiving an array that has 1..N number of userIds. I am building a unique list of those Ids so that I only query the user info once:

const uniqueUserIds = [
  ...new Set(requests.map((item) => Number(item.userId))),
];

With this list of unique user Ids, I'd like to build a task list to go out and get each of them before moving on to the next block of code.

var tasks: Observable<User>[] = [];
uniqueUserIds.map((userId) => {
  tasks.push(this.getUserInfo(userId));
});

The getUserInfo method just returns an Observable<User>:

getUserInfo(userId: number) {
  return this.userServiceHttpClient.getUser(userId);
}

I've tried using the following, but none of my Observables are executing:

Promise.all(tasks).then((value) => {
  console.warn(value);
});

If I take the value and do a .subscribe, then the observable is executed. Isn't there a way to take a list of Observables, all returning the same type, concatenate the results into an array, and then continue execution?

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

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

发布评论

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

评论(1

梦开始←不甜 2025-02-12 08:31:31

您不能使用promise.all()等待一系列可观察到的东西,因为它仅适用于承诺。

forkjoin来自RXJS的操作员是针对这种情况而制作的:)

import { forkJoin } from "rxjs";

forkJoin(
  uniqueUserIds.map(id => this.getUserInfo(id))
).subscribe(value => {
  console.log(value)
})

You can't use Promise.all() to await an array of Observables since it only works with Promises.

The forkJoin operator from RxJS was made exactly for this scenario :)

import { forkJoin } from "rxjs";

forkJoin(
  uniqueUserIds.map(id => this.getUserInfo(id))
).subscribe(value => {
  console.log(value)
})

Sandbox

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