我已经研究了一些实现Redux(NgRx)的Angular应用程序。 我不知道我当前项目的问题。
动作:
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) { }
}
减速器:
case UserActionTypes.GetUserFromStorageSuccess:
return {
...state,
user: action.payload,
error: ''
};
case UserActionTypes.GetUserFromStorageFail:
return {
...state,
error: action.payload
};
效果:
@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)))
))
);
在auth.service.ts中,我订阅了商店,并调度了一些操作。
this.store.dispatch(new userActions.GetUserFromStorage());
this.store.pipe(select(userReducer.getUser)).subscribe(
(user: User) => {
console.log('user TEST: ', user);
this.user = user;
}
);
我已经安装了ReduxDevTools。 将触发GetUserFromStorage操作,但不会触发getUserFromStorage $效果。 console.logged的'user TEST'值表明'user'为'null'。 有什么想法吗? 谢谢。
答案 0 :(得分:1)
确保您实际上已经“激活”了它们。
可注射的效果:
@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
])
]