Jordi
Jordi

Reputation: 23237

@ngrx: Subscription to Store called once it's created

My IStore is like:

export interface IStore {
  user: IUser;
  sources: ISourceRedux;
}

In LoginComponent I subscribe to IStore.user

private user$: Observable<IUser>;
private userSub: Subscription;
constructor(private store$: Store<IStore>)
{
    this.user$ = this.store$.select(state => state.user);
}

ngOnInit():void {
    this.userSub = this.user$.subscribe(
        (user: IUser) => {
            this.router.navigate(['/app']);
        },
        (error: any) => {
            this.addAlert(error.message);
        }
    );
}

The problem is that the "subscription is called" once it's just created.

Any ideas?

I've these effects:

@Injectable()
export class UserEffects {
  constructor(
    private _actions$: Actions,
    private _store$: Store<IStore>,
    private _userService: UsersService,
  ) { }

  @Effect({ dispatch: true })
  userLogin$: Observable<Action> = this._actions$
    .ofType('USER_REDUCER_USER_LOGIN')
    .switchMap((action: Action) =>
      this._userService.checkPasswd(action.payload.username, action.payload.password)
        .map((user: any) => {
          return { type: 'USER_REDUCER_USER_LOGIN_SUCCESS', payload: user };
        })
        .catch((err) => {
          return Observable.of({ type: 'USER_REDUCER_USER_LOGIN_FAILED', payload: { error: err } });
        })
    );
}

and reducers:

export class UserReducer {
  private static reducerName = 'USER_REDUCER';

  public static reducer(user = initialUserState(), {type, payload}: Action) {
    if (typeof UserReducer.mapActionsToMethod[type] === 'undefined') {
      return user;
    }

    return UserReducer.mapActionsToMethod[type](user, type, payload);
  }

    // tslint:disable-next-line:member-ordering
    /**
     * Default reducer type. I want all sources.
     */
    public static USER_LOGIN = `${UserReducer.reducerName}_USER_LOGIN`;

    /**
     * User login success.
     */
    public static USER_LOGIN_SUCCESS = `${UserReducer.reducerName}_USER_LOGIN_SUCCESS`;
    private static userLoginSuccess(sourcesRdx, type, payload) {
        return Object.assign(<IUser>{}, sourcesRdx, payload);
    }

    /**
     * User login fails.
     */
    public static USER_LOGIN_FAILED = `${UserReducer.reducerName}_USER_LOGIN_FAILED`;
    private static userLoginFailed(sourcesRdx, type, payload) {
        return Object.assign(<IUser>{}, sourcesRdx, payload);
    }

  // ---------------------------------------------------------------

  // tslint:disable-next-line:member-ordering
  private static mapActionsToMethod = {
      [UserReducer.USER_LOGIN_SUCCESS]: UserReducer.userLoginSuccess,
      [UserReducer.USER_LOGIN_FAILED]: UserReducer.userLoginFailed,
  };
}

Upvotes: 0

Views: 2327

Answers (1)

Sasxa
Sasxa

Reputation: 41264

You can try:

this.user$
  .skip(1)
  .subscribe(...)

if that's the only place where user is initialized in the Store. If that isn't working you can try few other operators to 'wait' for something...

this.user$
  .filter(user => user !== "some_inital_different_from_logout_state"
  .subscribe(...)

or add ready flag to the store

this.user$
  .skipUntil(this.store.select('ready'))
  .subscribe(...)

Update (explanation):

An action @ngrx/store/init is dispatched when store initializes and it triggers the first update, since all reducers return their part of the state tree if action didn't match:

export function someReducer(state: any, action: Action): any {
  switch (action.type) {
    default:
      return state;
  }
}

Upvotes: 2

Related Questions