gpt4 book ai didi

javascript - 处理多个项目后在 RxJS 中运行单个运算符

转载 作者:行者123 更新时间:2023-11-29 23:39:13 25 4
gpt4 key购买 nike

我是 RxJs 的新手,在处理了使用 switchMap 运算符发出的多个项目后,我无法链接单个操作。

场景:使用后端数据为下拉列表生成一个对象数组,然后链接一个操作来设置下拉列表的选定值。

这是帮助说明问题的非工作代码。

this.sub = this.dataService.getUserData()
.switchMap((data) => Observable.from(data)) // create new data stream from inner data set
.map((data: any) => {
return { value: data._id, viewValue: data.firstName + ' ' + data.lastName };
}) // create data structure for drop down
.subscribe( (data) => {
this.userDropDown.push(data); // this operation needs to run once per item emitted, and is working
this.patchFormData(); // <-- However, this only needs to run once
},
(error) => console.log("error", error)
);

我已经尝试了各种改变问题的运算符,但无法解决整个问题,即 a) 基于源数据获取新对象数组和 b) 完成后运行单个操作。

非常感谢任何帮助。

谢谢,

  • S。阿罗拉

-- 更新:工作的最终版本基于下面的答案,并进行了较小的语法修复:

this.sub = this.dataService.getUserData()
.map((data: any[]) => {
return data.map((x: any) => {
return { value: x._id, viewValue: x.firstName + ' ' + x.lastName };
});
})
.subscribe((data: any) => {
this.userDropDown = data;
this.patchFormData();
},
(error) => console.log("error", error)
);

最佳答案

实际上,您根本不需要.switchMap()。您只是使用 Observable.from() 创建了多个发射,这是完全没有必要的,除非您真的想一个一个地更新您的下拉值。

你可以做的只是返回数组,使用 .map()转换数组,然后将其分配给您的下拉值列表。

this.sub = this.dataService.getUserData()
//this map is a function of Observable
.map((data: any[]) => {
//this map is a function of array, not observable.
//use this to transform the data
return data.map(x => ({value: x._id, viewValue: x.firstName + ' ' + x.lastName}))
})
.subscribe((data) => {
//assign your values to your dropdown list, and not pushing it one by one.
this.userDropDown = data;
this.patchFormData();
},
(error) => console.log("error", error)
);

现在,您的 Observable 中只有一个发射(即 api 调用),然后在您的 .subscribe() 函数中,您的 this.userDropDownthis.patchFormData() 都只会运行一次。

关于javascript - 处理多个项目后在 RxJS 中运行单个运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45668855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com