问题描述
我有一个组件,其中包含一个包含锻炼数据的表格和一个按名称搜索的输入。以下代码完美运行。
searchTerm: FormControl;
searchTerms$: Observable<string>;
exercises$: Observable<Exercise[]>;
constructor(
private _exerciseService: ExerciseService,) {
this.searchTerm = new FormControl();
this.searchTerms$ = this.searchTerm.valueChanges;
this.exercises$ = this.searchTerms$.pipe(
startWith('' as string),debounceTime(1000),distinctUntilChanged(),switchMap(searchTerm => this._exerciseService.getExercisesByOrganization({ name: searchTerm,limit: 30,filter: 'full',offset: 0 }).pipe(
catchError(err => {
return EMPTY;
}))
),map((data) => data)
);
}
但现在,我必须为搜索实现更多过滤器(锻炼类型、带/不带设备、类别等),因此我想创建一个反应式表单并包含这些字段。像这样:
exerciseForm: FormGroup;
exerciseForm$: Observable<FormGroup>;
exercises$: Observable<Exercise[]>;
constructor(
private _exerciseService: ExerciseService,) {
this.exerciseForm = this._formBuilder.group({
name: new FormControl('',[]),requireEquipment: new FormControl(false,exerciseType: new FormControl('',});
this.exerciseForm$ = this.exerciseForm.valueChanges;
this.exercises$ = this.searchTerms$.pipe(
startWith('' as string),switchMap(formValue => this._exerciseService.getExercisesByOrganization(formValue).pipe(
catchError(err => {
return EMPTY;
}))
),map((data) => data)
);
}
通过这种方式,我可以根据选择的过滤器将完整表单发送到后端。我的问题是我该怎么做,因为 switchMap
中的“formValue”不是练习表单的值。我想将 JSON(可能使用响应式表单的 "getRawValue()"
函数)发送到后端,并根据用户搜索和过滤器处理其中的逻辑。
解决方法
使用 withLatestFrom()
向下游传递表单组对象
this.exercises$ = this.searchTerms$.pipe(
startWith('' as string),debounceTime(1000),distinctUntilChanged(),withLatestFrom(this.exerciseForm)
switchMap(([searchTerm,formGroup] =>...