I've worked on a few Angular apps that implemented Redux (NgRx). I can't figure out my current project's issue.
Actions:
export class GetUserFromStorage implements Action {
readonly type = UserActionTypes.GetUserFromStorage;
}
export class GetUserFromStorageSuccess implements Action {
readonly type = UserActionTypes.GetUserFromStorageSuccess;
constructor(public payload: User | null) { }
}
export class GetUserFromStorageFail implements Action {
readonly type = UserActionTypes.GetUserFromStorageFail;
constructor(public payload: string) { }
}
Reducer:
case UserActionTypes.GetUserFromStorageSuccess:
return {
...state,
user: action.payload,
error: ''
};
case UserActionTypes.GetUserFromStorageFail:
return {
...state,
error: action.payload
};
Effects:
@Effect() getUserFromStorage$:
Observable<userActions.GetUserFromStorageSuccess | userActions.GetUserFromStorageFail>
= this.actions$.pipe(
ofType(userActions.UserActionTypes.GetUserFromStorage),
tap(() => console.log('GETUserToStorage$', )),
mergeMap((action: userActions.GetUserFromStorage) =>
this.storageService.getItem(StorageKeys.USER).pipe(
map((user: User | null) =>
new userActions.GetUserFromStorageSuccess(user)),
catchError((error: string) =>
of(new userActions.GetUserFromStorageFail(error)))
))
);
In the auth.service.ts I subscribe to the Store and I dispatch some Actions.
this.store.dispatch(new userActions.GetUserFromStorage());
this.store.pipe(select(userReducer.getUser)).subscribe(
(user: User) => {
console.log('user TEST: ', user);
this.user = user;
}
);
I have ReduxDevTools installed. The GetUserFromStorage action fires, but it doesn't trigger the getUserFromStorage$ effect. The console.logged value of 'user TEST' shows that the 'user' is 'null'. Any ideas, anybody? Thank you.
Make sure you have actually "activated" them.
Effects injectable:
@Injectable()
export class FooEffects {
@Effect() getUserFromStorage$:
Observable<userActions.GetUserFromStorageSuccess | userActions.GetUserFromStorageFail>
= this.actions$.pipe(
ofType(userActions.UserActionTypes.GetUserFromStorage),
tap(() => console.log('GETUserToStorage$', )),
mergeMap((action: userActions.GetUserFromStorage) =>
this.storageService.getItem(StorageKeys.USER).pipe(
map((user: User | null) =>
new userActions.GetUserFromStorageSuccess(user)),
catchError((error: string) =>
of(new userActions.GetUserFromStorageFail(error)))
))
);
}
app.module.ts
:
import {EffectsModule} from '@ngrx/effects';
imports: [
EffectsModule.forRoot([
FooEffects
])
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With