FALLSEM2024-25_CSI3029_ETH_VL2024250102028_2024-09-06_Reference-Material-I.pptx
Document Details
Uploaded by Deleted User
Full Transcript
Service and Dependency Injection Module 4 What is Service? Angular Services are used to offer “services” to various components. These services could range from simple data entry to other complex functionalities. What is the Need for Angular Services? The c...
Service and Dependency Injection Module 4 What is Service? Angular Services are used to offer “services” to various components. These services could range from simple data entry to other complex functionalities. What is the Need for Angular Services? The concept of components in Angular. – The user interface of the application is developed by embedding several components into the main component. However, these components are generally used only for rendering purposes. They are only used to define what appears on the user interface. Ideally, other tasks, like data and image fetching, network connections, database management, are not performed. Then how are these tasks achieved? And what if more than one component performs similar tasks? Well, Services take care of this. – They perform all the operational tasks for the components. Services avoid rewriting of code. A service can be written once and injected into all the components that use that service A service could be a function, variable, or feature that an application needs What is Angular Services used for? Features independent of components such as logging services Share logic or data across components Encapsulate external interactions like data access Advantages – Services are easier to test. – They are easier to Debug. – We can reuse the service at many places. What Are Angular Services? Angular services are objects that get instantiated just once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e., data is available all the time. The main objective of a service is to organize and share business logic, models, or data and functions with different components of an Angular application. They are usually implemented through dependency injection. Features of Angular Services Features of Angular Services Services in Angular are simply typescript classes with the @injectable decorator. This decorator tells angular that the class is a service and can be injected into components that need that service. They can also inject other services as dependencies. These services are used to share a single piece of code across multiple components. These services are used to hold business logic. Services are used to interact with the backend. In angular, the components are singletons, meaning that only one instance of a service that gets created, and the same instance is used by every building block in the application. A service can be registered as a part of the module, or as a part of the component. To register it as a part of the component, you’ll have to specify it in the providers’ array of the module. Create Angular service An Angular service is plain Typescript class having one or more methods (functionality) along with @Injectable decorator. It enables the normal Typescript class to be used as service in Angular application. import { Injectable } from '@angular/core'; @Injectable() export class DebugService { constructor() { } } Here, @Injectable decorator converts a plain Typescript class into Angular service. Dependency injection (DI) Angular services may depend on another services to work properly. Dependency resolution is one of the complex and time consuming activity in developing any application. To reduce the complexity, Angular provides Dependency Injection pattern as one of the core concept. Dependency injection (DI) Dependency injection (DI) is the part of the Angular framework that provides components with access to services and other resources. Angular provides the ability for you to inject a service into a component to give that component access to the service. The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism. – Angular creates an application-wide injector for you during the bootstrap process, and additional injectors as needed. You don't have to create injectors. – An injector creates dependencies and maintains a container of dependency instances that it reuses, if possible. – A provider is an object that tells an injector how to obtain or create a dependency For any dependency that you need in your app, you must register a provider with the application's injector, so that the injector can use the provider to create new instances. For a service, the provider is typically the service class itself. When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the constructor parameter types. When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector makes one using the registered provider and adds it to the injector before returning the service to Angular. When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments. The process of HeroService injection looks something like this. Providing services You must register at least one provider of any service you are going to use. The provider can be part of the service's own metadata, making that service available everywhere, or you can register providers with specific modules or components. You register providers in the metadata of the service (in the @Injectable() decorator), or in the @NgModule() or @Component() metadata By default, the Angular CLI command ng generate service registers a provider with the root injector for your service by including provider metadata in the @Injectable() decorator. Register Angular service To use Dependency Injection, every service needs to be registered into the system. Angular provides multiple option to register a service. They are as follows − – ModuleInjector @ root level – ModuleInjector @ platform level – ElementInjector using providers meta data – ElementInjector using viewProviders meta data – NullInjector ModuleInjector @ root ModuleInjector enforces the service to used only inside a specific module. ProvidedIn meta data available in @Injectable has to be used to specify the module in which the service can be used. The value should refer to the one of the registered Angular Module (decorated with @NgModule). root is a special option which refers the root module of the application. The sample code is as follows − import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class DebugService { constructor() { } } ModuleInjector @ platform Platform Injector is one level higher than ModuleInjector and it is only in advanced and rare situation. We can configure platform level services using platformBrowser() method provided by PlatformModule. This is less common and is used for services that need to be shared across multiple Angular applications running on the same page. You can register these services in the platform injector. NullInjector NullInjector is one level higher than platform level ModuleInjector and is in the top level of the hierarchy. We could not able to register any service in the NullInjector. It resolves when the required service is not found anywhere in the hierarchy and simply throws an error. ElementInjector using providers ElementInjector enforces the service to be used only inside some particular components. providers meta data available in @Component decorator is used to specify the list of services to be visible for the particular component. ElementInjector using viewProviders viewProviders is similar to provider except it does not allow the service to be used inside the component content created using ng- content directive. Parent component can use a child component either through its view or content Resolve Angular service First, component tries to find the service registered using viewProviders meta data. If not found, component tries to find the service registered using providers meta data. If not found, Component tries to find the service registered using ModuleInjector If not found, component tries to find the service registered using PlatformInjector If not found, component tries to find the service registered using NullInjector, which always throws error. The hierarchy of the Injector along with work flow of the resolving the service Using Services to Display Employee Database Use Case: – Create employee details such as name, employee ID, and email ID. – Click on the employee button to retrieve an employee’s data – Add the location for the employees in the list D:\>ng new emp-app D:\emp-app>ng g service emp-list CREATE src/app/emp-list.service.spec.ts (379 bytes) CREATE src/app/emp-list.service.ts (145 bytes) Step 2: Create a service using the command, ng g service. We’ve created a service called emp-list. Once run, two files emp-list.service.ts and emp-list.service.spec.ts are created. The service consists of the employee data that needs to be displayed. We will be using an array for this purpose. info1: string[]=["Adam Taylor",'E354', '[email protected]'] With the agenda to retrieve this data in our component, we use a method, for the same. This method returns the employee data. getInfo1():string[]{ return this.info1 } Step 3: In order to retrieve this information in our app.component.ts, we need an array. infoReceived1: string[]=[]; As mentioned, services are implemented using dependency injection. We import the service class into the component.ts file. The key reason behind doing this is to tell Angular that when the component is created, an instance of the service class is also made to perform all the necessary tasks. We must also declare this instance in the providers’ array of the component. However, to access this instance, an object is created that can access the methods and variables of the service class. We’ve created the object empservice for the same. Now that you’ve learned how to create the service and inject it into the components, let’s move on to the UI of the application. We’re creating a button for each employee. Step 4: In the component.html file, we are creating an unordered list. We are also using the *ngFor directive to loop over the record fields. Employee1 {{info}}