This is the archived documentation for Angular v5. Please visit angular.io to see documentation for the current version of Angular.

Inject

npm Package @angular/core
Module import { Inject } from '@angular/core';
Source core/src/di/metadata.ts

A parameter decorator that specifies a dependency.

Metadata Overview

      
      @Inject({ 
  token: any
})
    

How To Use

      
      @Injectable()
class Car {
  constructor(@Inject("MyEngine") public engine:Engine) {}
}
    

Description

For more details, see the "Dependency Injection Guide".

Example

      
      class Engine {}

@Injectable()
class Car {
  constructor(@Inject('MyEngine') public engine: Engine) {}
}

const injector =
    ReflectiveInjector.resolveAndCreate([{provide: 'MyEngine', useClass: Engine}, Car]);

expect(injector.get(Car).engine instanceof Engine).toBe(true);
    

When @Inject() is not present, Injector will use the type annotation of the parameter.

Example

      
      class Engine {}

@Injectable()
class Car {
  constructor(public engine: Engine) {
  }  // same as constructor(@Inject(Engine) engine:Engine)
}

const injector = ReflectiveInjector.resolveAndCreate([Engine, Car]);
expect(injector.get(Car).engine instanceof Engine).toBe(true);