1

Below I have an example of what I am currently facing in the app:

app.module.ts

@NgModule({
  ...
  imports: [StoreModule.forRoot(reducers)],
  ...
})
export class AppModule {}

store

 users: {...}

articles.module.ts

@NgModule({
  ...
  imports: [StoreModule.forFeature('articles', reducers)],
  ...
})
export class ArticlesModule {}

User navigates to /articles and then the articles state slice will be added to the store

store

 users: {...},
 articles: {...}

Now, let's say initially, the store only has users, and within a component (belonging to users module), I am using a selector, the issue I have is that, I need to know in the selector if the articles slice has been added to the store or not, but I cannot use any articles selectors since I get this error

Cannot access 'selectArticles' before initialization....`

Is there a way to ask if the store contains a certain slice loaded?

Andres2142
  • 2,622
  • 2
  • 14
  • 19

1 Answers1

1

As you noticed, you can only use the selectors on Store data after the module with .forFeature is loaded.

To tackle it, you should load the store earlier, prior to using a selector on it. A good pattern is to create a separated module for your store and import it from the app.modules

I would suggest you add a app.store module as well. As the code grows, you will have to add more store modules.

new app.store.module:

@NgModule({
    imports: [
        StoreModule.forRoot(reducers),
        ...
        ArticleStoreModule
    ],
})
export class AppStoreModule {}

new article.store.module:

@NgModule({
    imports: [
        StoreModule.forFeature('articles', reducers)),
        ...
    ],
})
export class ArticleStoreModule {}

And than import you new AppStoreModule into you app.module

The Fabio
  • 5,369
  • 1
  • 25
  • 55
  • Even though I followed your suggestion, it didn't work completely, not sure why, but having modules within the store was a good call. so I managed to implement this in the project and it was helpful, thank you The Fabio! – Andres2142 Apr 29 '22 at 17:56