Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

Is it a good practice to create an Angular shared library and module that providers services from 3rd party libraries?

I'm working on an Angular project that will have two apps and a shared services module and likely shared feature modules. It seems a common practice to define a "Core" module that exports the CommonModule and FormsModule and other common components, pipes, and directives that the app and feature modules need. The Core module export them to make them all available from the one "Core" module. I am wondering if it also makes sense to do the same for services/providers that come from 3rd party libraries (for example a logging service). It seems I could write a forRoot() function in my Core module that returns all the providers from the 3rd party libraries that my apps depend on as a way to "bubble them up". Then each app module simply import CoreModule.forRoot() as a way to get a common set of dependencies (components, pipes, directives AND services) into the apps. Some 3rd party libraries can be configured and so the CoreModule.forRoot() could accept a configuration object to configure the various 3rd party modules.

question from:https://stackoverflow.com/questions/65943178/is-it-a-good-practice-to-create-an-angular-shared-library-and-module-that-provid

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I tried this out and discovered that it is not allowed to "bubble up" providers from 3rd-party library in your own library and then import your own library into an application. The approach I tried was to write a forRoot() function in the shared library that in-turn called LoggerModule.forRoot():

static forRoot(config: LoggerConfig): any[] {
  return [
    MyCoreModule,
    LoggerModule.forRoot(config),
  ];
}

The compiler reports an error saying that the forRoot() function could not be statically evaluated. So... I guess the answer to my original question is: No, you should not try and bubble-up the providers from a 3rd Party library. Instead, the application module should import the 3rd-party module directly. In my case that is:

  imports: [
    LoggerModule.forRoot({
      level: NgxLoggerLevel.DEBUG,
    }),
  ]

The original goal was to hide the 3rd-party libs & modules inside one "core" library was to create a sort of "platform" library. But that has its own drawbacks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...