Search code examples
angularngrxngrx-store

Verify existing feature state is added in NGRX Store


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?


Solution

  • 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