【问题标题】:NgRx selector returns undefinedNgRx 选择器返回未定义
【发布时间】:2020-05-11 06:59:03
【问题描述】:

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

【问题讨论】:

    标签: angular ngrx


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-08-31
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      相关资源
      最近更新 更多