构建并执行具有带打字稿和Angular变量的可观察物的动态列表
我正在收到一个具有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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能使用
promise.all()
等待一系列可观察到的东西,因为它仅适用于承诺。forkjoin
来自RXJS的操作员是针对这种情况而制作的:)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 :)Sandbox