Ask Your Question
1

What is the method for retrieving information from the store in an ngrx effect?

asked 2022-06-28 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-11-30 06:00:00 +0000

plato gravatar image

The method for retrieving information from the store in an ngrx effect is by using the select operator from the @ngrx/store package. Here's an example:

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { select, Store } from '@ngrx/store';
import { map, mergeMap } from 'rxjs/operators';
import { AppState } from '../app.state';
import { LoadUserAction, LoadUserSuccessAction, UserActionTypes } from './user.actions';
import { UserService } from './user.service';

@Injectable()
export class UserEffects {
  loadUser$ = createEffect(() =>
    this.actions$.pipe(
      ofType<LoadUserAction>(UserActionTypes.LOAD_USER),
      mergeMap(action => 
        this.store.pipe(
          select(state => state.auth.token),
          mergeMap(token => this.userService.getUser(action.payload.id, token)),
          map(user => new LoadUserSuccessAction(user))
        )
      )
    )
  );

  constructor(
    private actions$: Actions,
    private store: Store<AppState>,
    private userService: UserService
  ) {}
}

In this example, we're using the select operator to extract the token from the store, which we need to pass along with the user ID to the getUser method on the UserService. The result of that method call is then mapped to a new LoadUserSuccessAction that gets dispatched back to the store.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-28 11:00:00 +0000

Seen: 8 times

Last updated: Nov 30 '21