为什么 Angular 调用一个明显定义的对象未定义?

Why is Angular calling an obviously defined object undefined?

在我的 ngrx reducer 中,我声明了以下 initialState:

const initialState = {
homeState: {
    banner: {
        images: ['142_111421_HOMEPAGE_HERO-SLIDE_1_DESKTOP_EN.jpg', '5434424542.jpg'],
    }
  }
} 

在我的组件中,我从 reducer 中获取 initialState,如下所示:

private getHomeState = () => {
const homeState$ = this.store.select(state => {
  return state.homeState;
})

homeState$.subscribe((homeState) => {
    console.log('homeState', homeState)
    console.log('homeState.banner', homeState.banner)
    this.homeState = homeState;
  })
}

上面的订阅语句中有两个控制台日志。第一个 console.log('homeState', homeState) 按预期正确记录 homeState,并将横幅作为 homeState 的属性,如下所示:

homeState: {
  banner: {
    images: ['142_111421_HOMEPAGE_HERO-SLIDE_1_DESKTOP_EN.jpg', '5434424542.jpg'],
  }
}

但是 console.log('homeState.banner', homeState.banner) 说横幅是未定义的,即使它存在并且正确记录如上所示。

homeState.banner undefined

根据您的第一个控制台日志,homeState 是一个具有以下属性的对象:

homeState: {
  banner: {
    images: ['142_111421_HOMEPAGE_HERO-SLIDE_1_DESKTOP_EN.jpg', '5434424542.jpg'],
  }
}

因此要访问横幅,您需要使用:

homeState.homeState.banner