0

I am using @ngrx/data in an Angular 11 app, and I want to provide initial state to my Settings entity like you can do with @ngrx/store with StoreModule.forRoot({}, {initialState: someInitialState}.

What is the correct way to provide initial state to a @ngrx/data entity?

Thanks!

RcoderNY
  • 1,204
  • 2
  • 16
  • 23

1 Answers1

0

Use an effect or the constructor of a related module

export class DataModule {
  constructor(hero: HeroCollection, villain: VillainCollection, fight: FightCollection, store: Store) {
    hero.addManyToCache([]);
    villain.addManyToCache([]);
    fight.addManyToCache([]);
    // .....
  }
}
@Injectable()
export class EntityEffects {
  @Effect()
  public readonly data$ = this.actions$.pipe(
    ofType(ROOT_EFFECTS_INIT),
    // ....
  );
}
satanTime
  • 12,631
  • 1
  • 25
  • 73
  • Thank you for your response! I was hopping the `ROOT_EFFECTS_INIT` would be exactly what I need but unfortunately the @ngrx/data entities are not ready yet when that effect starts. I had the same problem using constructors in other services. The only place I found that is safe is in the ngOnInit of components but I need it a service. Is there some sort of hook in ngrx/data to signal when the EntityCache is ready to be accessed? Thanks! – RcoderNY Feb 06 '21 at 22:04
  • Why are they not ready? Usually the effect is called when all modules have been initialized, except lazy loaded of course. – satanTime Feb 06 '21 at 22:13
  • I'm not really sure. I made custom data services for my entities, so I put a console.log in each of my their `EntityCollectionDataService`s and can see the effect gets called in the middle of them being constructed. I have 5 entities and the effect gets called after like the 3 entities data services are constructed. I only made small adjustments to the data services, nothing that would come close to slowing them down, so I don't think that has to do with it. – RcoderNY Feb 06 '21 at 22:31
  • do you use subscriptions there? I would assume that they cause this delay, because redux / ngrx are straightforward and should be initiallized instantly. If you could provide stackblitz example - would be cool. That is where you could start from: https://stackblitz.com/github/satanTime/ngrx-entity-relationship-angular?file=src/app/app.component.ts – satanTime Feb 07 '21 at 09:01