0

I'm new to NGXS. So just to test, i've tried the simple setup on simple test app where you import the state in the app component using the forRoot and everything works fine.

Now I have a slightly bigger app and i've found the forFeature function for feature states. So in my module I have the following code:

imports: [...,
NgxsModule.forFeature([MyFeatureState]),
...]

Then I lazy load my modules in the routing module of each feature like this:

const routes: Routes = [
{
    path: '',
    component: AppComponent,
    children: [
        {path: '', redirectTo: 'my-feature', pathMatch: 'full'},
        {path: 'my-feature', loadChildren: './my-feature/my-feature.module#MyFeatureModule'},
    ]
}
];

Then here's my state class:

export interface MyFeatureStateModel {
  myFeatures: MyFeature[]
}

@State<MyFeatureStateModel>({
  name: 'myFeatures',
  defaults: {
    myFeatures: []
}
})
@Injectable()
export class MyFeatureState {
   constructor(private myFeatureService: MyFeatureService) {}

   @Select()
   static getAll(state: MyFeatureStateModel) {
      return state.myFeatures;
   }
 }

I have the following select on my display component:

@Select(MyFeatureState.getAll) myFeature$: Observable<any>;

There's a problem when selecting the data on the state. You'll notice i've used any for now as I don't know what's really being returned here, but when I subscribe to myFeature$ I can see the data and it's also being returned, but instead of returning just the data itself, it returns like this:

{myFeature: Array[]} // the array is the actual data

Also when I print to console the snapshot of the state I get the following:

{
  myFeature:
     myFeature: []
}

So what happens is when I subscribe I have an extra step like this:

this.myFeature$.subscribe((data: any) => {
  this.myFeature = data.myFeature;
  // previously I only have to do this.myFeature = data
});

This is all fine except that previously when I tried the forRoot I didn't have to do this.

Also, additional problem when I use the forFeature the state cannot automatically detect that the store already has data so it keeps on querying the backend even though there's already data in the store. I had to add an if statement which I think is not ideal. Also before when I use the forRoot it can automatically detect so the app only query the backend once and only on page load.

Any idea why these are happening?

Jed
  • 1,054
  • 1
  • 15
  • 34

1 Answers1

0

try this

this.myFeature$.subscribe(({data}) => {
  this.myFeature = data.myFeature;
});