Angular 2+ NGXS: state is undefined in directive notwithstanding the state defaults

733 views Asked by At

I have a problem with the NGXS library. I want to get a value out of my state using .selectSnapshot function but i always get undefined despite i had set defaults in my state. Maybe it has something to do with the lifecycle of the states and angular 2+ (on version 9 atm) in general. But as i use selectSnapshot or .select and .map to console.log my state value i recieve only undefined. I use the select-methods within a directive in the ngOnChanges-method and the directive is initialized on the front page (maybe it is initialized before the State is actually ready?). idk and i need help.

this.store.selectSnapshot(state => state.availableData)
this.store.select(state => state.availableData).pipe(map(state => console.log(state)))

i have tried to await the observable:

 private async getAvailableData(){
    return await this.store.select(state => state.availableData).pipe(map(data =>console.log(data))).toPromise();
  }

Maybe it has something to do with the DataModel of the DataState. So i also tried that select:

this.store.selectSnapshot((state: DataState) => state.availableData) // Throws error that availableData is not part of the DataState, but it is actually part of the DataStateModel.

I hope you can help me out. Thanks in advance

Edit:// I also tried that:

 this.store.selectSnapshot(state => state.datastore.availableData) // datastore is the state-name of the DataStore class

Edit2:// Here is a Stackblitz-Example: https://stackblitz.com/edit/ngxs-todo-example-czbmby?file=src%2Fapp%2Ftest.directive.ts

1

There are 1 answers

0
lkaupp On

Found the issue, you have to use the given name of the state at the @State-Definition:

so you have to use state..propertyoftheState

 this.store.selectSnapshot(state => state.datastore.availableData)// datastore is the state-name of the DataStore class

this was correct but i had a typo in my @State-Definition....