I have a reactive form:
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('')
});
};
This is my template:
<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>
After I click on "submit", I make a dispatch that save my data using a ngrx effect:
save() {
const user = this.formGroup.value;
if (user.id === null) {
this.store.dispatch(createUser({ user: user }));
} else {
this.store.dispatch(updateUser({ user: user }));
}
}
This is my effect:
public saveUser$ = createEffect(() =>
this.actions$.pipe(
ofType(createUser),
switchMap((action) =>
this.usuarioService.save(action.user).pipe(
map(() => loadUsers()),
catchError((error) => of(loadUsers()))
)
)
)
);
Someone can tell me if have one way to clear my reactive when my effect don't go to catchError?
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: ''
};
}
this.storeFormData$ = this.store.select(formData);
this.storeFormData.subscribe(formData => {
this.formGroup.setValue(formData);
});
this.usuarioService.save() is success your form will be cleared.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With