在NGRX效应之后处理动作

时间:2017-09-26 22:50:28

标签: javascript ngrx ngrx-effects

我有一个保存报告的NGRX效果,保存报告后我想重置表单并显示报告已保存的通知。

以下是商店调度效果以保存报告并将其注入商店的示例。

保存并插入后,我想重置表单并向用户显示通知。

onSubmit(): void {
  // Gather the fields from the form and
  // dispatch the new report event which will
  // save the report and insert it into the store
  const formModel = this.reportForm.value;
  this.store.dispatch(new AddReport(formModel));

  // After the report is saved, reset the form and
  // display a notification to the user it was saved
  this.reportForm.markAsPristine();
  this.snackbar.open('Report Saved!', null, { duration: 700 });
}

问题是我只想重置表单并在后端保存报表时显示通知。什么是实现这一目标的最佳方式。

1 个答案:

答案 0 :(得分:2)

效果应该返回一个新动作。

您有效调用API调用,然后如果成功,则返回一个操作,该操作将触发reducer以重置表单,然后调用一个影响来发送通知。

基本设置

reducers:
   successfullSubmit:
     const state = state.form = resetedform
     return state

effects
   formSubmit
     api.submitform
       on success return successfullSubmit
     catch
       on fail return submitFail
   successFullSubmit
     display notification

这就是为表单提交写入效果的方式

  @Effect()
  formSubmit$: Observable<Action> = this.actions$
    .ofType(actions.formSubmit)
    .map(toPayload)
    .switchMap(formStuffs =>
      this.api.submitForm(formStuffs)
        .map(() => new FormSubmitSuccess())
        .catch(error => of(new FormSubmitError(error))) 
    );