代码之家  ›  专栏  ›  技术社区  ›  amcdnl

处理NGRX效应后的动作

  •  0
  • amcdnl  · 技术社区  · 8 年前

    我有一个保存报告的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 回复  |  直到 8 年前
        1
  •  2
  •   Meeker    8 年前

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

    您具有进行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))) 
        );