如何提高 Rxjs 表达?

How to improve Rxjs expression?

save(): void {
 combineLatest(this.selectedSorting$, this.selectedFilters$)
                .pipe(
                    map((data) => {
                        let obj = {};
                        if (data[0]) {
                            obj['filters'] = data[0];
                        }
    
                        if (data[1]) {
                            obj['sorting'] = data[1];
                        }
    
                        return obj;
                    }),
                )
                .subscribe((response) => {
                    console.log(response);
                });

}

我观察到两个问题:

  1. 脏图运算符
  2. 未定义或 null observables 的问题this.selectedSorting$, this.selectedFilters$
  3. 当任何观察者发生变化时,它会影响save()

如何改进?

结果我期望一个对象来自:

{filters: []}
{sorting: []}
{filters: [], sorting: []}

我的完整代码:

public selectedFilters$ = new Observable();
public selectedSorting$ = new Observable();
public filterButtonDisabled$: Observable<any>;
public setttings$ = new Observable();

@ViewChildren(FilterComponent) filtersList: QueryList<FilterComponent>;

constructor(private settingsService: SettingsService, private applicationService: ApplicationService) {}

public saveSettings(): void {
    this.setttings$.subscribe((res) => console.log(res));
}

public resetFilter(): void {
    this.filtersList.forEach((flt) => flt.reset());
}

public doFilter(): void {
    this.selectedFilters$.pipe(switchMap((data) => this.applicationService.filterExecutionApplications(data))).subscribe();
}

public onSorting(sorted: any) {
    this.selectedSorting$ = of(sorted);
}

ngAfterViewInit() {
    this.selectedFilters$ = combineLatest(...this.filtersList.map((f) => f.changeFilter.pipe(filter((data) => !!data))));
    this.selectedFilters$.subscribe((data) => console.log(data));
    this.setttings$ = combineLatest(this.selectedSorting$, this.selectedFilters$).pipe(
        map((data) => ({ filters: data[1], sorting: data[0] })),
    );
}

我试图从 this.selectedSorting$this.selectedFilters$ 获取最后的更改并调用保存方法。但只有当用户点击按钮并调用 public saveSettings(): void {}

我明白你的意思了吗? 这对你有帮助吗?

save(): void {
  combineLatest(this.selectedSorting$, this.selectedFilters$)
     .pipe(
        map((data) => {
           let obj = {
              filters: [],
              sorting: []
           };

           obj.filters = data[0] || [];
           obj.sorting = data[1] || [];
                       
           return obj;
        }),
    ).subscribe((response) => {
         console.log(response);
    });

}

save(): void {
  combineLatest(
     this.selectedSorting$.pipe(map(response => response || [])),
     this.selectedFilters$.pipe(map(response => response || []))
    ).pipe(
        map((data) => {
           return {
              filters: data[0],
              sorting: data[1]
           };
        }),
    ).subscribe((response) => {
         console.log(response);
    });

}