【问题标题】:Is it possible to have ngrx store just for angular library?Is it possible to have ngrx store just for angular library?
【发布时间】:2022-12-02 02:37:57
【问题描述】:

I am trying to create a library that have its own ngrx store and implementation. In library's main module when I try to add StoreModule.forRoot(), there is no error. But in console I am seeing this issue. Am I doing something wrong?

main.js:1 ERROR Error: Uncaught (in promise): TypeError: StoreModule.forRoot() called twice. Feature modules should use StoreModule.forFeature() instead.
TypeError: StoreModule.forRoot() called twice. Feature modules should use StoreModule.forFeature() instead.

【问题讨论】:

    标签: angular ngrx ngrx-store


    【解决方案1】:

    Given that the library will always be imported into a running Angular app, and that that app's AppModule could have called StoreModule.forRoot(), you shouldn't call StoreModule.forRoot again in the library.

    Yes, the library compiles StoreModule.forRoot() successfully. The reason is that at compile time, Angular compiles the library independently and doesn't suspect that any consequent AppModule that will import this library could have called StoreModule.forRoot().

    I suppose that if your importer Angular app has no use of ngrx, that is, only the library uses ngrx, then maybe StoreModule.forRoot() in the library will work as you expect. But as it is not the case, try StoreModule.forFeature() in the library. It should still compile and work well without the error you got in the console.

    And yes the error you got in the console is self-explanatory. It simply tells you that StoreModule.forRoot() has been called twice and that you should rather import StoreModule.forFeature() in the library.

    If you are publishing this library to npm, I suggest you add an instruction to the README that AppModule should import StoreModule.forRoot(). While in your library's codebase, you import but StoreModule.forFeature(). So that if the developer has use of ngrx in their Angular app, they can still safely import StoreModule.forRoot().


    So from your question title:

    Is it possible to have ngrx store just for angular library?

    Yes. If the importer Angular module does not need ngrx, then the library can import StoreModule.forRoot(). However, if the importer Angular module uses StoreModule.forRoot(), the angular library should import but StoreModule.forFeature().

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 1970-01-01
      • 2022-12-19
      • 2022-12-01
      • 2022-12-28
      • 2022-12-02
      • 2022-12-01
      • 2022-12-02
      • 2022-12-02
      相关资源
      最近更新 更多