Pax*_*rce 12 ngrx ngrx-effects angular
我已经开发了一些实现 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) { }
}
Run Code Online (Sandbox Code Playgroud)
减速器:
case UserActionTypes.GetUserFromStorageSuccess:
return {
...state,
user: action.payload,
error: ''
};
case UserActionTypes.GetUserFromStorageFail:
return {
...state,
error: action.payload
};
Run Code Online (Sandbox Code Playgroud)
效果:
@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)))
))
);
Run Code Online (Sandbox Code Playgroud)
在 auth.service.ts 中,我订阅了 Store 并分派了一些操作。
this.store.dispatch(new userActions.GetUserFromStorage());
this.store.pipe(select(userReducer.getUser)).subscribe(
(user: User) => {
console.log('user TEST: ', user);
this.user = user;
}
);
Run Code Online (Sandbox Code Playgroud)
我安装了 ReduxDevTools。GetUserFromStorage 操作会触发,但不会触发 getUserFromStorage$ 效果。“user TEST”的 console.logged 值显示“user”为“null”。任何想法,任何人?谢谢你。
Chr*_*odz 16
确保您确实“激活”了它们。
注射效果:
@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)))
))
);
}
Run Code Online (Sandbox Code Playgroud)
app.module.ts:
import {EffectsModule} from '@ngrx/effects';
imports: [
EffectsModule.forRoot([
FooEffects
])
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4135 次 |
| 最近记录: |