I've recently delved into learning state management with NGXS. While things are going smoothly, I do have a couple of questions regarding specific scenarios:
How can I close a Mat Dialog box (or any div) only if an API call initiated from within it returns success?
Upon user logout, how can I reset states to their default values?
Here's a snippet of my code for the first scenario, including the action and dispatcher:
abc.action.ts
export class AddExamCategory {
static readonly type = '[ExamCategory] Add';
constructor(public payload: ExamCategory) {}
}
abc.state.ts
export interface ExamCategoryStateModel {
examCategoryList: ExamCategory[];
}
@State<ExamCategoryStateModel>({
name: 'examCategory',
defaults: {
examCategoryList: []
}
})
@Injectable()
export class ExamCategoryState {
constructor(private _adminService: AdminService) {}
@Action(AddExamCategory)
addExamCategory({ getState, patchState }: StateContext<ExamCategoryStateModel>, { payload }: AddExamCategory) {
return this._adminService.createExamCategory(payload).pipe(tap(response => {
patchState({ examCategoryList: [] }); // Want to close the modal/div after this part. If API returns ERROR do not close.
}));
}
}
abc.component.ts
this.store.dispatch(new AddAdminUser({ ...this.adminRegistrationForm.value, password: this.password.value }))
.subscribe(response => {
this.store.dispatch(new GetAdminUsers());
this.dialogRef.close(true)
});
The current behavior is closing the dialog regardless of the API response status.
For the second scenario, in the service where I handle the logout()
logic, I'm using this.store.reset({})
. While this resets the states, it doesn't revert them to their default values. How can I achieve that for multiple states during logout?
Appreciate any guidance on tackling these situations effectively.