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

1

8

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?

Laclos answered 7/8, 2018 at 0:59 Comment(0)
S
6

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)
   ])
);
Ship answered 7/8, 2018 at 5:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.