Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save anandakumarpalanisamy/ea2dfa95558dc825ecc1186acaca2433 to your computer and use it in GitHub Desktop.
Save anandakumarpalanisamy/ea2dfa95558dc825ecc1186acaca2433 to your computer and use it in GitHub Desktop.

ANGULAR DEPENDENCY INJECTION

Angular ships with its own Dependency Injection framework. This framework can also be used as a standalone module by other applications and frameworks.

To see what it can do when building components in Angular, start with a simplified version of HerosComponent that form the Tour of Heroes application.

src/app/heroes/heroes.component.ts

import { Component } from '@angular/core';

@Component ({
  selector: 'my-heroes',
  template: `<h2>Heroes</h2>
             <hero-list></hero-list>
             `
 })
 
 export class HeroesComponent { }
 
src/app/heroes/hero-list.component.ts

import { Component } from '@angular/core';

import { HEROES } from './mock-heroes';

@Component ({
   selector: 'hero-list',
   template: `
             <div *ngFor="let hero of heroes">
               {{hero.id}}-{{hero.name}}
             </div>
             `              
})

export class HeroListComponent {
   heroes = HEROES;
}

src/app/heroes/hero.ts

export class Hero {
   id:number,
   name:string,
   isSecret = false;
}

src/app/heroes/mock-heroes.ts

import { Hero } from './hero';

export var HEROES: Hero[] = [
 { id: 11, isSecret: false, name: 'Mr. Nice' },
 { id: 12, isSecret: false, name: 'Narco' },
 { id: 13, isSecret: false, name: 'Bombasto' },
 { id: 14, isSecret: false, name: 'Celeritas' },
 { id: 15, isSecret: false, name: 'Magneta' },
 { id: 16, isSecret: false, name: 'RubberMan' },
 { id: 17, isSecret: false, name: 'Dynama' },
 { id: 18, isSecret: true,  name: 'Dr IQ' },
 { id: 19, isSecret: true,  name: 'Magma' },
 { id: 20, isSecret: true,  name: 'Tornado' }  

];

The HerosComponent is the root component of the Heroes feature area. It governs all the child components of its area. This stripped down version has only one child, HeroListComponent, which displays a list of Heroes.

Right now HerosComponent get heroes from the HEROES, an in-memory collection defined in another file. That may suffice in the early stages of development, but it's far from ideal. As soon as you try to test this component or want to get your heroes data from a remote server, you'll have to change the implementation of heroes and fix every other use of the HEROES mock data.

It's better to make a service that hides how the app gets hero data.

Enter the services....

The following HeroService exposes a getHeroes() method that returns the same mock data as before, but none of its consumers need to know about it.

src/app/heroes/hero.service.ts

import { Injectable } from '@angular/core';

import { HEROES } from './mock-heroes';

@Injectable()
export class HeroService {
  getHeroes() { return HEROES; }
}

The @Injectable decorator above the service class is the one that makes the class available to an injector for instantiation.

Of course, it isn't a real service. If the app were actually getting data from a remote server, the API would have to be asynchronous, perhaps returning a Promise. You'd also have to rewrite the way components consume the service.

A service is nothing more that a class in Angular. It remains nothing more than a class until you register it with an Angular Injector.

Configuring the Injector

You don't have to create an Angular injector. Angular application creates an application wide injector for you during the bootstrapping process.

src/main.ts (bootstrap)

platformBrowserDynamic().bootstrapModule(AppModule);

You do have to configure the injector by registering the providers that creates the services the application requires.

___ You can either register a provider with an NgModule or in application components.___

Registering providers in an NgModule

Here's the AppModule that registers two providers, UserService and an APP_CONFIG provider, in its providers array.

src/app/app.module.ts (RootModule - excerpt only)

@NgModule ({
   imports: [ BrowserModule ],
   declarations: [
      AppComponent,
      CarComponent,
      HeroesComponent,
      /* ... */
   ],
   providers: [
      UserService,
      { provide: APP_CONFIG, useValue: HERO_DI_CONFIG }      
   ],
   bootstrap: [ AppComponent]
})

export class AppModule { }

Because the HeroService is used only within the HeroesComponent and its child components, the top-level HeroesComponent is the ideal place to register it.

Register providers in a component

Here's a revised version of HeroesComponent that registers the HeroService in its providers array.

src/app/heroes/heroes.component.ts

import { Component } from '@angular/core';

import { HeroService } from './hero.service'

@Component ({
    selector: 'my-heroes',
    providers: [ HeroService ],
    template: `
              <h2>Heroes</h2>
              <hero-list></hero-list>
              `
})

export class HeroesComponent { }

When to use NgModule versus an application component

  • On the one hand, a provider in NgModule is registered in the root injector. That means that every provider registered within an NgModule will be accessible in the entire application.

  • On the other hand, a provider registered in an application component is available only to that component and all its children.

Here, the APP_CONFIG service needs to be available all acrros the application, so it's registered in the AppModule @NgModule providers array. But, since the HeroService is only used within the Heroes feature area and nowhere else, it makes sense to register it in the HerosComponent.

Preparing the HeroListComponent for injection

The HeroListComponent should get heroes from the injected HeroService. Per the dependency injection pattern, the component must ask for the service in its constructor, as discussed in DEPENDENCY INJECTION section.


import { Component } from '@angular/core';

import { Hero } from './hero';

import { HeroService } from './hero.service';

@Component ({
    selector: 'hero-list',
    template: `
              <div *ngFor="let hero of heroes">
                {{hero.id}}-{{hero.name}}
              </div>
              `              
})

export class HeroListComponent {
    heroes: Hero[];
    
    constructor (heroService: HeroService) {
      this.heroes = heroService.getHeroes();
    }
}

Note that constructor parameters has the type HeroService, and that the HeroListComponent class has an @Component decorator. Also recall that the parent component HeroesComponent has providers information for HeroService.

The constructor parameter type, the @Component decorator, and the parent's providers information combine to tell the Angular injector to inject an instance of HeroService wherever it creates a new HeroListComponent.

Implicit Injector creation

You could create such an injector explicitly:

injector = ReflectiveInjector.resolveAndCreate([Car, Engine, Tires]);
let car = injector.get(Car);

You won't find code like that in the Tour of Heroes or any of the other documentation samples. You could write code that explicitly creates an injector if you had to, but it's not always the best choice. Angular takes care of creating and calling injectors when it creates components for you—whether through HTML markup, as in (TAG: hero-list), or after navigating to a component with the router. If you let Angular do its job, you'll enjoy the benefits of automated dependency injection.

Singleton services

Dependencies are singletons within the scope of the injector. In this guide's example, a single HeroService instance is shared among the HeroesComponent and its HeroListComponent children.

However, Angular DI is a hierarchial injection system, which means that nested injectors can create their own instances of services.

Testing the component

Earlier you saw that designing a class for Dependency injection makes the class easier to test. Listing dependencies as constructor parameters may be all you need to test application parts effectively.

For example, you can create a new HeroListComponent with a mock service that you can manipulate under test:

let expectedHeroes = [{name:'A'}, {name: 'B'}]
let mockService = <HeroService> {getHeroes: () => expectedHeroes }

it('should have heroes when HeroListComponent is created', () => {
  let hlc = new HeroListComponent(mockService);
  expect(hlc.heroes.length).toEqual(expectedHeroes.length);
});

When the servie needs a service

The HeroService is very simple. It doesn't have any dependencies of its own.

What if it had a dependency ? What if it reported its activities through a logging service ? You'd apply the same constructor injection pattern, adding a constructor that takes a Logger parameter.

Here is the revision compared to the original;

import { Injectable } from '@angular/core';

import { HEROES ) from './mock-heroes';
import { Logger } from '../logger.service';

@Injectable()
export class HeroService {
  
  constructor (private logger: Logger) { }
  
  getHeroes() {
    this.logger.log('Getting heroes ...');
    return HEROES;
  }
}

The Constructor now asks for an injected instance of a Logger and stores it in a private property called logger. You call the property within the getHeroes method when anyone ask for heroes.

Why @Injectable()

@Injectable marks a class available to an injector for instantiation. Generally speaking, an injector reports an error when trying to instantiate a class that is not marked as @Injectable.

As it happens, you could have omitted @Injectable from the first version of HeroService because it had no injected parameters. But you must have it now that the service has an injected dependency. You need it because Angular requires constructor parameters metadata in order to inject a Logger.

SUGGESTION: ADD @INJECTABLE() TO EVERY SERVICE CLASS

Consider adding @Injectable to every service class, even those that don't have any dependencies and, therefore, do not technically require it; Here's why;

  • Future proffing: No need to remember @Injectable() when you add any dependency later.
  • Consistency: All services follow the same rules, and you don't have to why decorator is missing.

Injectors are also responsible for instantiating components like HeroComponent. So why doesn't HerosComponent have @Injectable()?

You can add it, if you really want to. It isn't necessary because the HeroComponent is already marked with @Component, and this decorator class (like @Directive or @Pipe, which you learn about later) is a subtype of @Injectable(). It is in fact @Injectable decorators that identify a class as a target for instantiation by an injector.

Key note:

  • At runtime, injectors can read class metadata in the transpiled JavaScript code and use the constructor parameter type information to determine which things to inject.

  • Not every JavaScript class has metadata. The TypeScript compiler discards metadata by default. If the emitDecoratorMetadata compiler option is true (as it should be in the tsconfig.json), the compiler adds the metadata to the generated JavaScript for every class with at least one decorator.

  • While any decorator will trigger this effect, mark the service class with the @Injectable() decorator to make the intent clear.

ALWAYS INCLUDE THE PARENTHESES

Always write @Injectable(), not just @Injectable. The application will fail mysteriously if you forget the parentheses.

Creating and Registering a logger service

Inject a logger into HeroService in two steps:

  • Create the logger service
  • Register it with the application

The logger service is quite simple.

import { Injectable } from '@angular/core';

@Injectable()
export class logger {
  logs: string[] = [];
  
  log(message: string){
    this.logs.push(message);
    console.log(message);
  }
}

You're likely to need the same logger service everywhere in your application, so put it in the project's app folder and register it in the providers array of the application module, AppModule.

providers: [Logger]

If you forget to register the Logger, Angular throws an exception when it first looks for the logger;

EXCEPTION: No provider for Logger! (HeroListComponent -> HeroService -> Logger)

That's Angular telling you that the dependency injector couldn't find the provider for the logger. It needed that provider to create the Logger to inject to a new HeroService, which it needed to create and inject into a new HeroListComponent.

The chain of creations started with the Logger provider.

Injector providers

A provider provides the concrete, runtime version of the dependency value. The injector relies on providers to create instances of the services that the injector inject into components and other services.

You must register a service provider with the injector, or it won't know to create the service.

Earlier you registered the logger service in the providers array of metadata for the AppModule like this;

providers: [ Logger ]

There are many ways to provide something that looks and behaves like a Logger. The Logger class itself is an obvious and natural provider. But it's not the only way.

You can configure the injector with alternative providers that can deliver an object that behaves like a Logger.

  • You could provide a substitute class.
  • You could provide a logger-like object.
  • You could give it a provider that calls a logger factory function.

Any of these approaches might a good choice under the right circumstances. What matters is that the injector has a provider to go to when it needs a Logger.

The Provider class and provide object literal

You wrote the providers array like this;

providers: [ Logger ]

This is a shorthand version of a provider registration using a provider object literal with two properties;

[{ provide: Logger, useClass: Logger }]

The first is the token that serves as the key for both locating a dependency value and registering the provider.

The second is a provider definition object, which you think of a receipe for creating the dependency value. There are many ways to create a dependency value just as there are many ways to write a receipe.'

Alternative Class Providers

Occasionally you'll ask a different class to provide the service. The following code tells the injector to return a BetterLogger when something asks for the Logger.

[{ provide: Logger, useClass: BetterLogger }]

Class provider with dependencies

May be an EvenBetterLogger could display the user name in the log message. This logger gets the user from the injected UserService which is also injected at the application level.

@Injectable()
class EvenBetterLogger extends Logger {
  constructor (private userService: UserService) { super(); }
  
  log(message: string){
    let name = this.userService.user.name;
    super.log(`Message to ${name}: ${message}`);    
  }
}

Another way of configuring it is;

[UserService,
    {provide: Logger, class: EvenBetterLogger}]

Aliased class providers

[ NewLogger,
  // Not aliased! Creates two instances of `NewLogger`
  { provide: OldLogger, useClass: NewLogger}]

The solution: alias with the useExisting option.

[ NewLogger,
  // Alias OldLogger w/ reference to NewLogger
  { provide: OldLogger, useExisting: NewLogger}]

Value providers

Sometime's its easier to provide a ready-made object rather than ask the injector to create it from a class.

// An Object in the shape of the logger service

let silentLogger = {
  logs: ['silent logger says "Shhhh!". Provided via "useValue"']
  log: () => {} 
};

Then you register a provider with the useValue option, which takes this object play the logger role.

[{ provide: Logger, useValue: silentLogger }]

Optional Dependencies

The HeroService requires a Logger, but what if it could get by without a Logger ? You can tell Angular that the dependency is Optional by annotating the constructor argument with @Optional.

import { Optional } from '@angular/core';
constructor (@Optional() private logger: Logger) {
  if(this.logger){
    this.logger.log(some_message);
  }
}

When you @Optional(), your code must be prepared for a null value. If you don't register a logger somewhere up in the line, the injector will set the value of logger to null.

Factory Providers

Sometimes you need to create the dependent value dynamically, based on information you won't have until last possible moment. Maybe the information changes repeatedly in the course of browser session.

Suppose also that the injectable service has no independent access to the source of this information.

This situation calls for a factory provider.

To illustrate this point, add a new business requirement: the HeroService must hide secret heroes from normal users. Only authroized users should see secret heroes.

Like the EvenBetterLogger, the HeroService needs a fact about the user. It needs to know if the user is authorized to see secret heroes. The authorization can change during the course of a single application session, as when you log in a different user.

Unlike EvenBetterLogger, you can't inject the UserService into the HeroService. The HeroService won't have direct access to the user information to decide who is authorized and who is not.

Instead, the HeroService constructor takes a boolean flag to control the display of secret heroes.

constructor(
  private logger: Logger,
  private isAuthorized: boolean) { }

getHeroes() {
  let auth = this.isAuthorized ? 'authorized ' : 'unauthorized';
  this.logger.log(`Getting heroes for ${auth} user.`);
  return HEROES.filter(hero => this.isAuthorized || !hero.isSecret);
}

You can inject the Logger, but you can't inject the boolean isAuthorized. You'll have to take over the creation of new instances of this HeroService with a factory provider.

A factory provider needs a factory function.

let heroServiceFactory = (logger: Logger, userService: UserService) = {
  return new HeroService(logger, userService.user.isAuthorized);
}

Although the HeroService has no access to the UserService, the factory function does.

You inject both Logger and the UserService into the factory provider and let the injector pass them to the factory function:

export let heroServiceProvider =
  { provide: HeroService, 
    useFactory: heroServiceFactory,
    deps: [Logger, UserService]
  }
  • The useFactory field tells Angular that the provider is a factory function whose implementation is the heroServiceFactory.

  • The deps property is an array of provider tokens. The Logger and UserService classes serves as a token for their class providers. The injector resolves these tokens and injects the corresponding services into the matching factory function parameters.

Notice, that you captured the factory provider in an exported variable, heroServiceProvider. This extra step makes the factory provider reusable. You can register the HeroService with this variable wherever you need it.

So, rewriting the HerosComponent would be like below;

import { Component }          from '@angular/core';
import { heroServiceProvider } from './hero.service.provider';
@Component({
  selector: 'my-heroes',
  template: `
  <h2>Heroes</h2>
  <hero-list></hero-list>
  `,
  providers: [heroServiceProvider]
})
export class HeroesComponent { }

Dependency Injection Tokens

When you register a provider with an injector, you associate that provider with a dependency injection token. The injector maintains an internal map of token-provider map that it references when asked for a dependency. The token is the key to the map.

In all the previous examples, the dependency value has been a class instance, and the class type had been the lookup key.

For example, here you get a HeroService directly from the injector by supplying the HeroService type as a token;

heroService: HeroService

You have similar good fortune when you write a constructor that requires an injected class-based dependency. When you define a constructor parameter with the HeroService class type, Angular knows to inject the service associated with the class token/key called HeroService.

constructor (heroService: HeroService)

This is especially convenient when you consider that most dependency values are provided by classes.

Non-class dependencies

What if the dependency value isn't a class ?

Sometimes the thing that you want to inject is a string, function or object.

Applications often define configuration objects with lots of small facts (like the title of application or the address of the API endpoint), but these configuration objects aren't always instances of a class. They can be object literals such as this one.

export interface AppConfig {
  apiEndpoint: string;
  title: string;
}

export const HERO_DI_CONFIG: AppConfig = {
  apiEndpoint: 'api.heroes.com',
  title: 'Dependency Injection'
};

What if you'd like to make this configuration object available for injection? You know you can register an object with a value provider

But what should you use as token ? You don't have a class type to serve as a token. There is no AppConfig class.

TypeScript interfaces aren't valid tokens.

The HERO_DI_CONFIG constant has an interface, AppConfig. Unfortunately, you cannot use a TypeScript interface as a token:

//FAIL ! Can't use interface as provider token
[{provide: AppConfig, useValue: HERO_DI_CONFIG}]
//FAIL ! Can't use AppConfig interface as a parameter type
constructor (private config: AppConfig) { }

That seems strange if you're used to dependency injection in strongly typed languages, where an interface is the preferred dependency lookup key.

It's not Angular's doing. An interface is a TypeScript design-time artifact. JavaScript doesn't have interfaces. The TypeScript interface disappears from the generated JavaScript. There is no interface type information left for Angular to find at runtime.

Injection Token

One solution to choosing a provider token for non-class dependencies is to define and use an Injection Token. The definition of such a token looks like this;

import { InjectionToken } from '@angular/core';

export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');

The type parameter, while optional, converys the dependency's type to the tooling and developers. The token description is another developer aid.

Register the dependency provider using the InjectionToken object:

providers: [{provide: APP_CONFIG, useValue: HERO_DI_CONFIG}]

__Now you can inject the configuration object into any constructor that needs it, with the help of an @Inject decorator.

constructor (@Inject(APP_CONFIG) config: AppConfig){
  this.title = config.title;
}

Although the AppConfig interface plays no role in dependency injection, it supports the typing of the configuration object within the class.

Alternatively, you can provide and inject the configuration object in an NgModule like AppModule.

TODO (find out the write example)


+makeExcerpt('src/app/app.module.ts', 'ngmodule-providers')

Summary

You learned the basics of Angular dependency injection in this page. You can register various kinds of providers, and you know how to ask for an injected object (such as service) by adding a parameter to a constructor.

Angular dependency injection is more capable than this guide has described. You can learn more about its advanced features, beginning with its support for nested injectors, in Hierarchical Dependency Injection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment