在处理多个项目后在RxJS中运行单个操作
我对RxJs比较新,在处理使用switchMap运算符发出的多个项目后无法链接单个操作。在处理多个项目后在RxJS中运行单个操作
场景:使用后端数据为下拉列表生成对象数组,然后链接单个操作以设置下拉列表的选定值。
下面是有助于说明问题的非工作代码。
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)
);
我已经试过了变形的问题,但我无法来解决这个问题,即一个)的整体获取新的对象基于阵列的断源数据和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)
);
,你只有一个发射在你的观察,(这是API调用),然后在你的.subscribe()
功能,您this.userDropDown
和this.patchFormData()
都将只运行一次。
不幸的是,.switchmap服务需求.. getUserData调用依赖于graphql,它为我提供了一个单独的用户集合。 switchMap将该单个集合转换为单独发射的项目(每个用户一个),然后我可以使用映射一个一个地转换。我想过使用lodash来处理整个系列,但如果可能的话,我试图坚持使用RxJs的方法。 – sarora
@sarora正是我的答案的重点,你**不需要通过观察者一个接一个地转换它们。您可以使用数组的['.map'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)来转换它们。 – CozyAzure
谢谢!我没有想到要在RxJs管道内用常规的.map操作符操作集合..非常漂亮!一旦我开始使用.switchmap方法,就会让连锁操作变得不必要地困难。 – sarora
是'this.dataService.getUserData()'返回一个数组? – CozyAzure