【问题标题】:run single operation in RxJS after mutliple items are processed处理多个项目后在 RxJS 中运行单个运算符
【发布时间】:2018-01-21 22:59:28
【问题描述】:

我对 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)
    );

【问题讨论】:

  • this.dataService.getUserData() 是否返回一个数组?

标签: javascript arrays rxjs rxjs5


【解决方案1】:

实际上,您根本不需要.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() 都只会运行一次。

【讨论】:

  • 不幸的是,.switchmap 满足了需求。getUserData 调用依赖于 graphql,它为我提供了一个可供使用的用户集合。 switchMap 将该单个集合转换为单独发出的项目(每个用户一个),然后我可以使用 map 一个一个地进行转换。我曾想过使用 lodash 来处理整个集合,但如果可能的话,我会尝试坚持使用 RxJs 方法。
  • @sarora 这正是我回答的重点,您不需要需要通过可观察对象逐一转换它们。您可以使用数组的.map 转换它们。
  • 谢谢!我没想到用常规的 .map 运算符 within RxJs 管道来操作集合。非常漂亮!一旦我进入了 .switchmap 方法,它就使链接单个操作变得不必要地困难。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-15
  • 2016-12-26
  • 2021-01-02
  • 2020-10-07
相关资源
最近更新 更多