ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Angular Injector, @Injectable & @Inject

The Angular Injector lives at the core of Angular Dependency injection system. In this article, we will look at it in more detail. We will also take a look at the @Injectable & @Inject decorators.

What is Angular Injector

The providers Angular Injector is responsible for instantiating the dependency and injecting it into the component or service.

The Injector looks for the dependency in the Angular Providers using the Injection token. The Angular Providers array returns the Provider, which contains the information about how to create the instance of the dependency. The Injector creates the instance and injects it into the Component or service.

When is Angular Injector is created

The Angular creates two Injector trees when the Application bootstraps. One is the ModuleInjector tree for the Modules and the other one is the ElementInjector tree which is for the Elements (Components & Directives etc).

The Angular loads the Root Module (named as AppModule) when the application bootstraps. It creates RootModule Injector for the Root Module. This Injector has an application-wide scope. The RootModule Injector becomes part of the ModuleInjector Tree.

Angular Root Module loads the AppComponent, which is the root component of our app. The AppComponent gets its own Injector. We call this root Injector. This Injector becomes the root of the ElementInjector tree.

The Root Component contains all other components. Angular App will create child components under the Root Component. All these child component can have their own child components creating an Injector tree closely mimicking the component tree. These Injectors become part of the ElementInjector tree.

The Every Injector gets its own copy of providers.

Registering the service with injector

We register all dependencies of the application with the Providers. Every injector has a Provider associated with it. The Providers metadata of @NgModule, @Component or @Directive is where we register our dependency

                              
 
providers: [ProductService, LoggerService]
                            
                        

Where you register your dependency defines the scope of the dependency. The dependency registered with the Module using @NgModule decorator is attached the Root Provider (Provider attached to the Root Injector). This Dependency is available to entire application.

The dependency registered with the component is available to that component and any child component of that component.

Another way to register the dependencies is to use the ProvidedIn property of the Injectable decorator

@Injectable

The Injectable is a decorator, which you need to add to the consumer of the dependency. This decorator tells angular that it must Inject the constructor arguments via the Angular DI system

Example of Injectable

We created an example application in the Angular Dependency injection tutorial. It had two services LoggerService & ProductService as shown below.

LoggerService
                              

import { Injectable } from '@angular/core';
 
@Injectable()
export class LoggerService {
  log(message:any) {
    console.log(message);
  }
}
 
                            
                        
ProductService
                              
 
import { Injectable } from '@angular/core';
 
import {Product} from './Product'
import {LoggerService} from './logger.service'
 
@Injectable()
export class ProductService{
 
    constructor(private loggerService: LoggerService) {
        this.loggerService.log("Product Service Constructed");
    }
 
    public  getProducts() {
 
        this.loggerService.log("getProducts called");
        let products:Product[];
 
        products=[
            new Product(1,'Memory Card',500),
            new Product(1,'Pen Drive',750),
            new Product(1,'Power Bank',100)
        ]
 
        this.loggerService.log(products);
        return products;               
    }
}
                            
                        

The ProductService has a dependency on the LoggerService. Hence it is decorated with the @Injectable decorator. Remove @Injectable() from ProductService and you will get the following error.

That is because withoutDI Angular will not know how to inject LoggerService into ProductService.

Remove @Injectable() from LoggerService will not result in any error as the LoggerService do not have any dependency.

The Components & Directives are already decorated with @Component & @Directive decorators. These decorators also tell Angular to use DI, hence you do not need to add the @Injectable().

The injectable decorator also has the ProvidedIn property using which you can specify how Angular should provide the dependency.

                              


@Injectable({  
   providedIn: 'root'
})
export class SomeService{
}
 
                            
                        

@Inject

The @Inject() is a constructor parameter decorator, which tells angular to Inject the parameter with the dependency provided in the given token. It is a manual way of injecting the dependency

In the previous example, when we removed the @Injectable decorator from the ProductService we got an error.

We can manually inject the LoggerService by using the @Inject decorator applied to the parameter loggerService as shown below.

The @Inject takes the Injector token as the parameter. The token is used to locate the dependency in the Providers.

                              


export class ProductService{
    constructor(@Inject,(LoggerService) private loggerService) {
        this.loggerService.log("Product Service Constructed");
    }
}