Angular NgRx 选择器无法读取未定义的 属性

Angular NgRx selector cannot read property of undefined

所以我需要帮助,试图找出我的学校项目示例,该示例是关于将 NgRx 与 api 服务一起使用。

我在 ngrx 选择器 createSelector() 中遇到错误,无法读取未定义的 属性。

这里是 StackBlitz:https://stackblitz.com/github/NikolaLukic1/ngrx-example

我想我搞砸了 reducers,或者 app.module.ts

您的选择器不好。首先你必须检查那个状态是否有属性调用'posts'然后请求它,这是最近常见的问题。

在这里您可以找到您的 stackBlitz 更新和工作。

您需要的代码在这里:

import { createSelector } from '@ngrx/store';

const selectPosts = (state: any) => state.hasOwnProperty('posts') ? state.posts : '';

export const selectedPosts = createSelector(
  selectPosts,
  (state: any) => {
    return state.hasOwnProperty('posts') ? state.posts : '';
  }
);

我在这些场景中使用安全导航运算符。

export const selectIsVerified = createSelector(
    selectCurrentUser,
    user => user?.emailVerified
)

这样,属性 在可用之前不会被读取(如果确实可用的话)。