【问题标题】:How can i filter and map with Switch Map in one statement?如何在一个语句中使用 Switch Map 进行过滤和映射?
【发布时间】:2020-02-03 04:26:08
【问题描述】:

我有一个发射器,它发出一个对象数组,如下例所示。

ServerDropdownOption
name: "Just Closed Buyers"
selected: true
value: "leadbucket::07727388-500A-4ED0-BB5A-1BB4718F1AFC"
__proto__: Object

我使用的代码使用 switchMap 只返回每个对象的值。

this.chipsSelect.multiSelectBox.onSave
  pipe(
  takeWhile(_ => this.alive),
  filter((tag) => tag.selected === 'true'),
  switchMap(updatedSelection => this.contactsService.updateBuckets(this.contactId, updatedSelection.map(tag => tag.value))) )
  .subscribe();

我现在需要的是还根据所选值进行过滤,并返回该值为 true 的值。问题是它会产生以下错误。

类型“IOptionMultiSelectBox[]”上不存在属性“selected”

export interface IOptionMultiSelectBox {
    name: string;
    value: any;
    selected: boolean;
}

所以我的 IOptionMultiSelectBox 具有 selected 属性,但从我的 observable 返回的 dat 是一个对象数组。那么我该如何解决这个问题,以便过滤器正常工作?

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    代替 rxjs filter,使用 map,然后使用 JS array.prototype filter 来获取 selected,它们是 true

    this.chipsSelect.multiSelectBox.onSave
      pipe(
        takeWhile(_ => this.alive),
        map((tags: IOptionMultiSelectBox[]) => tags.filter(tag => tag.selected == true)),
        // .....
    

    【讨论】:

    • 您能否提供一些见解,为什么它抱怨使用过滤器时选择的不存在? IOptionMultiSelectBox 具有该属性,我发出的是这些对象的数组,因此它也应该存在于那里
    • 因为selected不存在于tags数组中,它存在于tags中的每个tag中,但是你尝试使用tags.selected,这将不起作用。
    【解决方案2】:

    我通过在发射过程之前实际应用过滤器使其工作

    save(optionsList: IOptionMultiSelectBox[]) {
    this.onSave.emit(optionsList.filter(data => data.selected === true));
    this.toggleDirective.close();
    }
    

    在这种情况下,它不会抱怨所选的属性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多