I've built a Store
interface:
export interface IStore {
user: IUser;
}
where IUser
is:
export interface IUser {
id: string;
name: string;
username: string;
customer: string;
}
In my component I create a subscription to IStore.user
:
export class LoginComponent implements OnInit {
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']); ((((1))))
},
(error: any) => {
this.addAlert(error.message);
}
);
}
ngOnDestroy():void {
this.userSub.unsubscribe();
}
public login():void {
this.store$.dispatch({ type: 'USER_REDUCER_USER_LOGIN' });
}
}
Currently, ((((1))))
code is reached inmediatly subscription is just built. Nevertheless, the desired behavior is to reach ((((1)))) callback
when 'USER_REDUCER_USER_LOGIN' action is dispatched in
login()` method.
This is my UserReducer.ts
:
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,
};
}
and initialUserState()
is:
export function initialUserState(): IUser {
return {
id: '',
name: '',
username: '',
customer: ''
};
};
Any ideas?
EDIT
@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_ERROR',
payload: { error: err }
});
})
);
}