如何与恢复初始对象一起使用某些过滤器?

时间:2018-12-07 12:01:06

标签: javascript typescript rxjs

我有对象this.fltUsers的数组。

下面,我监听传入的邮件并过滤this.fltUsers

this.filterForm.controls["gender"].valueChanges.subscribe(selectedValue => {
      this.requestLoadPersonal = this.fltUsers.filter((p: Personal) => {
        return selectedValue ? p.gender == selectedValue : true;
      });
    });

    this.filterForm.controls["position"].valueChanges.subscribe(
      selectedValue => {
        this.requestLoadPersonal = this.fltUsers.filter((p: Personal) => {
          return selectedValue ? p.positionId == selectedValue : true;
        });
      }
    );

this.requestLoadPersonal包含已过滤的数据。

如何将第一次过滤的结果传递给第二个?要在两个AND之间建立条件filters? 如何恢复初始对象?

也许我可以像这样使用替换

if (this.requestLoadPersonal !== this.fltUsers) {
    // FILTER BY this.requestLoadPersonal
} else {
   // FILTER BY this.fltUsers
}

似乎我每次更改之前都必须存储对象的语句,然后才能将其恢复到上一个​​语句。

1 个答案:

答案 0 :(得分:1)

我假设您正在使用rxjs。如果是这样,您可以使用rxjs运算符。 也许看看文档here

您可能会这样做:

const firstCondition = this.filterForm.controls["gender"].valueChanges.pipe(map(selectedValue => {
  this.fltUsers.filter((p: Personal) => p.gender == selectedValue);
}));

const secondCondition = this.filterForm.controls["position"].valueChanges.pipe(map(
  selectedValue => {
    this.fltUsers.filter((p: Personal) => p.positionId == selectedValue);
  }));

merge(firstCondition, secondCondition).pipe(reduce((acc, val) => acc && val), true);

我正在将两个可观测值都映射到您的状况(pipemap)。然后,我可以使用merge创建一个包含两个值的单个可观察流,并reduce最终将其存储为单个布尔值。