微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular Reactive Forms - 在更改事件时调用 API

如何解决Angular Reactive Forms - 在更改事件时调用 API

我有一个组件,其中包含一个包含锻炼数据的表格和一个名称搜索的输入。以下代码完美运行。

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] =>...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。