From the instantiation of Angular Component and Directive, talk about the origin of the command of Angular forRoot method

Different from the singleton feature of Angular service, Angular components and directives are usually instantiated multiple times. For example, every time the selector of Component appears in HTML markup, an instantiation of Component will be triggered.

The scope of these Component and Directive is limited to the NgModule that imports them, to prevent naming conflicts, eg two components might have the same selector. It is because of this difference in Angular's Dependency Injection (DI) behavior that NgModule that contains components and directives needs to be distinguished from ModuleWithProviders that contain components, directives, Providersand . This is where the forRoot() method comes in.

However, dependency injection is not always this simple. Sometimes during the bootstrap process, the NgModule for all applications is not available. Lazy loading is one such example. providersWhen a NgModule is lazy loaded during routing , providers and their children registered in the lazy loaded NgModule are not available during bootstrap, at which point Angular cannot register them. Therefore, they are only added as providers when routes are loaded, and they are 作用域injected starting from the lazy loaded NgModule and its submodules.

If multiple lazy loaded NgModules try to register the same provider, each node of the NgModule tree will end up with a different instance. By importing the provider at the root, it helps ensure that all lazy loaded NgModules get the same instance of the provider, which is why forRoot() is so named.

insert image description here

As a consumer, when a library dependency used in the application layer requires a lazy-loaded NgModule, its forRoot method needs to be called. Import the module at the root of the application and register it with the forRoot() method to import the provider globally. In other NgModules, when components and directives need to be imported, use the appropriate non-root form of import.

insert image description here

Guess you like

Origin blog.csdn.net/i042416/article/details/126415559