NgRx 选择器 returns 未定义

NgRx selector returns undefined

我对 NgRx 选择器有疑问,returns 未定义。所有的动作都被调度并且效果和减速器被触发。但是返回值未定义。

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 方法时,我在组件中未定义。 当我使用异步管道(只是为了测试)时,它按预期工作。 但是我需要更新一个表单值... 我哪里遗漏了什么?

我认为你的问题是解析器,你似乎是直接在商店中使用管道运算符而不是先使用 select 运算符,你还应该添加一个过滤器(v => !!v ) 确保只有 returns 当配置文件不再未定义时,配置文件在加载时未定义并且第一个操作员将得到未定义的,这将使您的解析器在未定义时呈现 UI 并且您ngOnInit 得到一个未定义的值。 作为个人喜好,我不倾向于按照您的方式使用解析,因为它不允许您在加载配置文件时添加加载部分,我认为最好在 ngInit 中触发 loadProfile你的组件并添加一个 isLoading 属性 到你可以通过 select 或

查询的状态