Ostn
Ostn

Reputation: 813

NGXS - how to use one action handler on multiple streams

I have several actions that run asynchronously, let say VerifyEmail and changepassword. I would like to show a loader when the action starts and hide it when the auction ends. I know I can do it for each action this way :

this.actions$
    .pipe( ofActionDispatched(VerifyEmail) )
    .subscribe( () => {
        this.showLoader();
    });
this.actions$
    .pipe( ofActionSuccessful(VerifyEmail) )
    .subscribe( () => {
        this.hideLoader();
    });

But it is two blocks for each async actions, I was wondering if there is a way to combine several actions into a single pipe? something like ofActionDispatched([VerifyEmail, ChangePassword]) ?

Upvotes: 1

Views: 3112

Answers (1)

Mark Whitfeld
Mark Whitfeld

Reputation: 6848

You can combine the operator for multiple actions like this:

ofActionDispatched(VerifyEmail, ChangePassword)

Note that it is just addition arguments to the method not an array.

As an alternative you could bind this loader to a loading prop somewhere in your state and update that from your respective @Action handlers before and after doing the async work:

@Action(VerifyEmail)
async verifyEmail(ctx, action){
    ctx.patchState({ loading: true });
    await someasyncWork();
    ctx.patchState({ loading: false });
}

Yet another option is to call this from the UI component before and on completion of the dispatch:

this.showloader();
this.store.dispatch(new VerifyEmail())
    .subscribe(() => this.hideLoader());

Hope this helps.

Upvotes: 8

Related Questions