[英]NgRx selector returns undefined
我对 NgRx 选择器有疑问,它返回未定义。 所有的动作都被调度,效果和减速器被触发。 但是返回的值是未定义的。
account.actions.ts
export const loadProfile = createAction('[Account Resolver] Load Profile');
export const profileLoaded = createAction('[Load Profile Effect] Profile Loaded', props<{ profile: Profile }>());
account.effects.ts
loadProfile$ = createEffect(() =>
this.actions$.pipe(
ofType(AccountActions.loadProfile),
concatMap(() => this.accountService.getProfile()),
map((profile: Profile) => profileLoaded({ profile }))
)
);
account.reducer.ts
export const accountReducer = createReducer(
initialAccountState,
on(AccountActions.profileLoaded, (state, action) => {
return {
...state,
profile: action.profile
};
}),
)
account.resolver.ts
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
return this.store.pipe(
tap(() => {
if (!this.loading) {
this.loading = true;
this.store.dispatch(loadProfile());
}
}),
first(),
finalize(() => (this.loading = false))
);
}
account.selectors.ts
export const selectAccountState = createFeatureSelector<fromAccount.AccountState>('account');
export const selectProfile = createSelector(selectAccountState, account => account.profile);
account.component.ts
ngOnInit() {
this.store
.pipe(
select(selectProfile),
tap(profile => {
this.profileForm.patchValue(profile);
}),
takeUntil(this.destroy)
)
.subscribe();
}
在这里,在调用 patchValue 方法时,我在组件中未定义。 当我使用异步 pipe(只是为了测试)时,它按预期工作。 但是我需要更新表单值...我在哪里遗漏了什么?
我认为您的问题是解析器,您似乎直接在商店中使用 pipe 运算符,而不是首先使用 select 运算符,您还应该添加一个过滤器(v =>,.v),以确保它仅在配置文件时返回不再未定义,加载时配置文件未定义,第一个操作员将获得未定义,这将使您的解析器在未定义时呈现 UI,并且您的 ngOnInit 获得未定义的值,作为个人偏好,我不倾向于以您正在执行的方式使用解决方案,因为它不允许您在加载配置文件时添加加载部分,我认为最好在组件的 ngInit 中触发 loadProfile 并将 isLoading 属性添加到您的 state 中您可以通过选择器查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.