在ngrx成功执行操作后,如何清除表单?

时间:2020-05-17 06:56:58

标签: angular ngrx

我有一个反应形式:

const createFormGroup = (dataItem?: Usuario) => {
  if (dataItem) {
    return new FormGroup({
      id: new FormControl(dataItem.id),
      nome: new FormControl(dataItem.nome),
      cidade: new FormControl(dataItem.cidade)
    });
  }
  return new FormGroup({
    id: new FormControl(),
    nome: new FormControl(''),
    cidade: new FormControl('')
  });
};

这是我的模板:

<form (ngSubmit)="save()" [formGroup]="formGroup">
   <input formControlName="nome" type="text" class="form-control" id="inputName" placeholder="Nome">
   <input formControlName="cidade" type="text" class="form-control" id="exampleInputPassword1"
   <button id="my-element" type="submit" class="btn btn-primary">Complete
   </button>
</form>

点击“提交”后,我将使用ngrx效果进行分配以保存数据:

save() {
  const user = this.formGroup.value;
  if (user.id === null) {
    this.store.dispatch(createUser({ user: user }));
  } else {
    this.store.dispatch(updateUser({ user: user }));
  }
}

这是我的效果

public saveUser$ = createEffect(() =>
  this.actions$.pipe(
    ofType(createUser),
    switchMap((action) =>
      this.usuarioService.save(action.user).pipe(
        map(() => loadUsers()),
        catchError((error) => of(loadUsers()))
      )
    )
  )
);

有人可以告诉我,当我的效果没有达到catchError时,是否有一种方法可以清除我的反应性?

5 个答案:

答案 0 :(得分:1)

  • 如果您想以ngrx的方式进行操作,请根据您对成功的影响调用另一个操作。
saveUser$ = createEffect(() =>
    this.actions$.pipe(
        ofType(createUser),
        switchMap((action) =>
            this.usuarioService.save(action.user).pipe(
                map(() => {
                    loadUsers();
                    return new clearFormAction();
                }),
                catchError((error) => of(loadUsers()))
            )
        )
    )
);
  • clearFormAction()的化简器中将表单数据重置为空(通常为初始状态)。
case clearFormAction: {
    return {
        ...state,
        id: '',
        nome: '',
        cidade: ''
    };
}
  • 订阅组件ngOnInit()中的商店表单数据
this.storeFormData$ = this.store.select(formData);
this.storeFormData.subscribe(formData => {
    this.formGroup.setValue(formData);
});
  • 因此,只要您的this.usuarioService.save()成功,您的表格就会被清除。

答案 1 :(得分:1)

如果仅在确定操作已成功分派之后才想清除表单,我将设置一个简单的服务,并在this.usuarioService.save成功后根据您的效果对其进行更新: >

效果:

您需要将Subject导入效果文件:

import { Subject } from 'rxjs';

然后添加如下所示的服务。这可能在单独的文件中,但是为了简单起见,请将其添加到效果文件的顶部,紧随所有“导入”的下方

@Injectable({
  providedIn: 'root'
})
export class ClearFormService {
  private clearFormSource = new Subject<boolean>();
  clearForm$ = this.clearFormSource.asObservable();
  clearForm() {
    this.clearFormSource.next(true);
  }
}

接下来,将此服务添加到效果类的构造函数中:

constructor(private clearFormService: ClearFormService) { }

如果构造函数中已经有引用,请添加:

private clearFormService: ClearFormService

...到最后。

然后this.usuarioService.save成功时,您就可以更新此服务中的可观察对象。注意大括号已添加到map中。有“更多的rxjs”方法,但是我认为这很好:

public saveUser$ = createEffect(() =>
  this.actions$.pipe(
    ofType(createUser),
    switchMap((action) =>
      this.usuarioService.save(action.user).pipe(
        map(() => {
            this.clearFormService.clearForm(); // Updates your service
            return loadUsers();
        }),
        catchError((error) => of(loadUsers()))
      )
    )
  )
);

具有表单的组件:

然后在带有表单的组件中,您需要从效果文件中导入ClearFormService并将其添加到构造函数中,与效果文件中的操作相同。您可能还需要导入subscription

import { Subscription } from 'rxjs';

然后您可以订阅clearForm$,并在收到回复时清除表格。

clearFormSubscription = new Subscription();

ngOnInit() {
    this.clearFormSubscription = this.clearFormService.clearForm$.subscribe(response => {
        this.formGroup.reset()
        console.log('Clear Form Here');
    })
  }

别忘了取消订阅onDestroy!

ngOnDestroy() {
    this.clearFormSubscription.unsubscribe()
}

您可以设置一个使用您的ngrx存储的解决方案,但是我认为这会过度设计。

答案 2 :(得分:0)

您可以使用this.formGroup.reset()来清除该反应形式中的数据。

如果您只需要重置特定字段,则也可以使用this.formGroup.patch()

例如:-您只需要重置nomecidade字段。然后,您可以使用它。

this.formGroup.patch(
 {
   nome: null,
   cidade:null
 }
)

OR

this.formGroup.controls['nome'].reset();
this.formGroup.controls['cidade'].reset();

答案 3 :(得分:0)

使用 This.formGroup.reset()根据您要清除表单值的条件来重置表单

答案 4 :(得分:0)

也许只是观察组件中的状态,如果某个特定属性指示操作已成功执行,则进行所有重置。

ngOnInit(): void {
    this.watchOperations();
    // ...
}

watchOperations(): void {
    this.store
    .pipe(
        select(state => state.todos.succeeded)
    )
    .subscribe(succeeded => {
        if (succeeded) {
            this.store.dispatch(LOAD());
            this.formSubmitted = false;
            this.form.reset(this.formDefaults);
        }
    });
}

谈到效果:

createEffect(() => this.actions$.pipe(
    ofType(ADD),
    mergeMap(({ payload }) => {
      return this.todosService.add(payload)
        .pipe(
          map(() => ({ type: '[Todos] Add Success' })),
          catchError(() => of({ type: '[Todos] Add Fail' }))
        );
    })
));

组件:

addTodo(): void {
    this.formSubmitted = true;

    if (this.form.valid) {
        this.store.dispatch(ADD({
            payload: {
                ...this.form.value,
                done: false
            } as ITodo
        }));
    }
}

和减速器:

// ...
on(ADD, (state, action) => {
    return {
        ...state,
        processed: action.payload,
        processing: true
    };
}),
on(ADD_SUCCESS, (state) => {
    return {
        ...state,
        processing: false,
        succeeded: true
    };
}),
on(ADD_FAIL, (state) => {
    return {
        ...state,
        processing: false,
        succeeded: false
    };
}),
// ...