ProviderBuilder

export class ProviderBuilder

exported from angular2/core defined in angular2/src/core/di/provider.ts (line 388)

Helper class for the bind function.

Constructor

constructor(token: any)

Not Yet Documented

Members

token

Not Yet Documented

toClass(type: Type) : Provider

Binds a DI token to a class.

(live demo)

Because toAlias and toClass are often confused, the example contains both use cases for easy comparison.

class Vehicle {} class Car extends Vehicle {} var injectorClass = Injector.resolveAndCreate([ Car, provide(Vehicle, {useClass: Car}) ]); var injectorAlias = Injector.resolveAndCreate([ Car, provide(Vehicle, {useExisting: Car}) ]); expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car)); expect(injectorClass.get(Vehicle) instanceof Car).toBe(true); expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car)); expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);

toValue(value: any) : Provider

Binds a DI token to a value.

(live demo)

var injector = Injector.resolveAndCreate([ provide('message', {useValue: 'Hello'}) ]); expect(injector.get('message')).toEqual('Hello');

toAlias(aliasToken: /*Type*/ any) : Provider

Binds a DI token to an existing token.

Angular will return the same instance as if the provided token was used. (This is in contrast to useClass where a separate instance of useClass will be returned.)

(live demo)

Because toAlias and toClass are often confused, the example contains both use cases for easy comparison.

class Vehicle {} class Car extends Vehicle {} var injectorAlias = Injector.resolveAndCreate([ Car, provide(Vehicle, {useExisting: Car}) ]); var injectorClass = Injector.resolveAndCreate([ Car, provide(Vehicle, {useClass: Car}) ]); expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car)); expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true); expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car)); expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);

toFactory(factory: Function, dependencies?: any[]) : Provider

Binds a DI token to a function which computes the value.

(live demo)

var injector = Injector.resolveAndCreate([
  provide(Number, {useFactory: () => { return 1+2; }}),
  provide(String, {useFactory: (v) => { return "Value: " + v; }, deps: [Number]})
]);

expect(injector.get(Number)).toEqual(3);
expect(injector.get(String)).toEqual('Value: 3');