Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the correct way to dispatch an action in angular?

could you please tell me what is the correct way to dispatch an action.

In the component, we do like that using store using store.dispatch than action.

onLoginButtonClick(user: Authenticate) {
    this.store.dispatch(new Authctions.Login(user));
  }

Now using ngEffect we dispatch action without using store only use new Action name why ?

export class AuthEffect {
  @Effect()
  login$ = this.actions$.pipe(
    ofType(AuthActionsTypes.LOGIN),
    map((action: Login) => action.payload),
    switchMap((auth: Authenticate) => {
      return this.authService.login(auth).pipe(
        map(user => new LoginSuccess({user})),
        catchError(error => of(new LoginFailure(error)))
      );
    })
  );

why it is used like this

 new LoginSuccess({user})

can we used like this this.store.dispatch( new LoginSuccess({user})) ? in effect ?

any update?

like image 966
user944513 Avatar asked Aug 07 '18 00:08

user944513


1 Answers

Effects return Actions, like the documentation here states.

Ngrx will internally dispatch the action returned from your effect.

You could directly use this.store.dispatch( new LoginSuccess({user})) in an effect, but you shouldn't as it is not needed and will only clutter your code!

If you need to dispatch multiple actions from your effect you can do something like this:

@Effect() save = this.update$.pipe(
   map(action => action.payload),
   switchMap(payload => this.myService.save(payload)),
   switchMap(res => [
       new NotificationAction('save success'),
       new SaveSuccessAction(res)
   ])
);
like image 51
Wannes Van Dorpe Avatar answered Sep 26 '22 16:09

Wannes Van Dorpe