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

Inject

A constructor parameter decorator that specifies a custom provider of a dependency.

OptionDescription
token

Injector token that maps to the dependency to be injected.

See also

Options

Injector token that maps to the dependency to be injected.

token: any
      
      token: any
    

Usage notes

The following example shows a class constructor that specifies a custom provider of a dependency using the parameter decorator.

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);
      
      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, the Injector uses the type annotation of the parameter as the provider.

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);
      
      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);