In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you the example analysis of angular services, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!
Dependency injection
Creating a service requires the Injectable,@Injectable () decorator to mark the class as an injectable service, but Angular cannot actually inject it anywhere until the provider for that service has configured Angular's dependency injector.
Provider tells the injector how to create the service, and you can configure the injector by setting metadata (in 3 ways):
In the @ Injectable () decorator of the service itself.
In NgModule's @ NgModule () decorator.
In the @ Component () decorator of the component.
The @ Injectable () decorator has a metadata option called providedIn, where you specify that the provider of the decorated class be placed in the root injector, or in the injector of a particular NgModule.
Both the @ NgModule () and @ Component () decorators have a providers metadata option where you can configure NgModule-level or component-level injectors.
Injector and service instance
Within the scope of an injector, the service is singleton. The application has only one root injector, and angular has a multi-level injector system, so that the subordinate injector can create its own service instance.
Whenever Angular creates a component instance with providers specified in @ Component (), it also creates a new child injector for that instance. Similarly, when a new NgModule (that is, lazy module) is loaded at run time, Angular can create an injector with its own provider for it.
With the injector inheritance mechanism, full application-level services can still be injected into these components. The injector of a component is a child node of its parent component injector, and a descendant of the parent node of its parent node, and so on, until the root injector is applied. Angular can inject services provided by any injector in the inheritance pedigree.
When modular programming, service, component, pipe and so on had better be placed in module. When these services need to be introduced, they should be referenced by importing module instead of import service and component directly, which is not in line with the idea of modularization.
Multistage injection system
There is an injector tree parallel to the component tree in the application, and at what level of injection will eventually result in:
The final packet size
Scope of servic
The life cycle of the service
When provider is specified in the @ Injectable () decorator of the service itself, the optimization tool used in the CLI production model can perform tree-shaking optimization, which removes unused services, resulting in smaller packages.
Three-level provider
Root level, is AppModule global, the configuration method has been mentioned.
NgModule level, two methods: you can specify it in the provider metadata of @ NgModule of module, or you can specify a module class in the providerIn option of @ injectable ()
If the module is lazy modole, you need to use the provider option of @ NgModule.
Component-level configuration of its own injector for each component instance
Whether for a root-level injector or a module-level injector, the lifetime of the service instance is the same as the application or module itself. Angular can inject this service instance into any class that needs it (that is, it is singleton within app). Angular can only inject the corresponding service into the component instance or its subordinate component instance, but not into the service instance elsewhere (that is, the component is not singleton).
Injector bubbling
When a component requests a dependency, Angular first tries to satisfy it with the component's own injector. If the injector of the component does not find the corresponding provider, it transfers the request to the injector of its parent component for processing. If that injector does not satisfy the application, it continues to transfer to its parent injector in the injector tree. The application continues to bubble up-until Angular finds an injector that can process the application or exceeds its ancestral location in the component tree. If the ancestor in the component tree has not been found, Angular throws an error.
Singleton service
There are two ways to create a singleton service in angular:
Declare that the service is provided at the root of the application when the service is created
Include the service in AppModule or a module that will only be imported by AppModule
The first one here is easy to understand. The second point: when a serivce is declared through @ NgMododule (), the service will be singleton in the AppModule. When a service is provided in a module, and when another lazy module imports the module, angular will create a sub-injector for it and recreate an instance of service. This service will have one more instance.
ForRoot ()
If a module provides both a service provider and declarable objects (components, instructions, pipes), multiple instances of the service provider will be generated when it is loaded in a child injector (such as lazy module). The existence of multiple instances can cause problems because they mask the instance of the service provider in the root injector, which may be intended to be used as a singleton object. Therefore, Angular provides a way to separate the service provider from the module so that the module can be imported by the root module with providers or without the providers quilt module.
As mentioned above, when a new NgModule (that is, lazy module) is loaded during runtime, Angular can also create an injector for it, so the service in other imported modules generates multiple instances, and forRoot ensures that instead of creating a new service instance, it references the service instance in the root injector, which ensures that service is still a singleton service.
Code
Import the TestDIModule module with service in the lazy loading module
@ NgModule ({imports: [CommonModule, BatteryRoutingModule, TestDIModule], declarations: [BatteryWidgetComponent, BatteryTwoComponent, DemoComponent]})
In the TestDIModule module
@ NgModule ({imports: [CommonModule], declarations: [TestDiComponent], exports: [TestDiComponent], providers: []}) export class TestDIModule {static forRoot (): ModuleWithProviders {return {ngModule: TestDIModule, providers: [TestDiService]};}
Introduce the TestDIModule module into the root module
Imports: [BrowserModule, TestDIModule.forRoot (),]
Finally, add this lazy loading module to the root module routing.
Const routes: Routes = [{path: 'battery', loadChildren:'. / battery-widget/battery.widget.module#BatteryWidgetModule'},]; @ NgModule ({exports: [RouterModule], imports: [RouterModule.forRoot (routes)],})
As a test, you can type log in service in TestDIModule to see
Import {Injectable, ModuleWithProviders} from'@ angular/core';import {TestDIModule} from'. / test-di.module'@Injectable () export class TestDiService {constructor () {console.log (- > TestDiService');} addCoount () {this.count++; console.log (- > count', this.count);} count = 0;} above is all the content of the article "sample Analysis of angular Services". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.