Home > other >  Why is Angular calling an obviously defined object undefined?
Why is Angular calling an obviously defined object undefined?

Time:11-18

In my ngrx reducer, I declare the following initialState:

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

In my component, I fetch the initialState from the reducer as shown below:

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;
  })
}

There are two console logs in the subscribe statement above. The first one, console.log('homeState', homeState), correctly logs the homeState as expected with the banner as an attribute of homeState as shown below:

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

But console.log('homeState.banner', homeState.banner) says banner is undefined even though it is present and correctly logged as shown above.

homeState.banner undefined

CodePudding user response:

As per your first console log homeState is an object that has the following properties:

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

so to access banner, you need to use:

homeState.homeState.banner
  • Related