Angular 在一个表单输入上形成 RxJS 多重过滤器

Angular Form RxJS multiple filter on one form input

我有以下要过滤的对象数组

companies = [
    {
      division: "Company 1",
      departments: ["Department 1", "Department 2", "Department 3"]
    },
    {
      division: "Company 2",
      departments: ["Department 2", "Department 3", "Department 4"]
    },
    {
      division: "Company 3",
      departments: ["Department 3", "Department 4", "Department 5"]
    }
    ...
  ]

我可以在单个表单输入上使用值更改订阅来过滤除法。

this.myForm.valueChanges.pipe(
    debounceTime(400),
    distinctUntilChanged(),
    tap(val => {
      let searchTerm = val.searchString;
      this.filteredDivisions = this.companies.filter((company) =>
        company.division
          .toLowerCase()
          .indexOf(searchTerm.toLowerCase()) !== -1)

    })
  ).subscribe()

有人要求我根据一个输入对部门和部门数组进行过滤。因此,如果用户键入 Department 1,则只会显示公司 1,但用户也可以在同一输入框中键入 Company 1,然后也只会显示公司 1。 用户应该能够键入部门或部门来过滤数组。

那么如何设置过滤器以使用相同的输入同时过滤部门和部门?

好吧,您只需要扩大一些将与给定字符串匹配的字段

this.myForm.valueChanges
    .pipe(
        debounceTime(400),
        distinctUntilChanged(),
        tap(val => {
            let searchTerm = val.searchString.toLowerCase();
            this.filteredDivisions = this.companies.filter(company => {
                // filter against the 'division' property
                const divisionMatch =
                    company.division.toLowerCase().indexOf(searchTerm) !== -1;

                // filter against the 'departments' property
                const departmentsMatch = () =>
                    company.departments.find(
                        department => department.toLowerCase().indexOf(searchTerm) !== -1,
                    );

                // If divisionMatch is true, no need to check further, return true
                return divisionMatch || departmentsMatch();
            });
        }),
    )
    .subscribe()

我把你的注意力集中在 departmentsMatch 是一个函数,而不是一个简单的值,这允许惰性计算。如果 division 匹配,则永远不会调用 departmentsMatch