FactoryProvider

Stable Interface

What it does

Configures the Injector to return a value by invoking a useFactory function.

How to use

1
2
3
function serviceFactory() { ... }
 
const provider: FactoryProvider = {provide: 'someToken', useFactory: serviceFactory, deps: []};

Interface Overview

1
2
3
4
5
6
interface FactoryProvider {
  provide : any
  useFactory : Function
  deps : any[]
  multi : boolean
}

Interface Description

For more details, see the Dependency Injection Guide.

Example

1
2
3
4
5
6
7
8
9
10
11
12
const Location = new OpaqueToken('location');
const Hash = new OpaqueToken('hash');
 
const injector = ReflectiveInjector.resolveAndCreate([
  {provide: Location, useValue: 'http://angular.io/#someLocation'}, {
    provide: Hash,
    useFactory: (location: string) => location.split('#')[1],
    deps: [Location]
  }
]);
 
expect(injector.get(Hash)).toEqual('someLocation');

Dependencies can also be marked as optional:

1
2
3
4
5
6
7
8
9
10
11
const Location = new OpaqueToken('location');
const Hash = new OpaqueToken('hash');
 
const injector = ReflectiveInjector.resolveAndCreate([{
  provide: Hash,
  useFactory: (location: string) => `Hash for: ${location}`,
  // use a nested array to define metadata for dependencies.
  deps: [[new Optional(), new Inject(Location)]]
}]);
 
expect(injector.get(Hash)).toEqual('Hash for: null');

Interface Details

provide : any

An injection token. (Typically an instance of Type or OpaqueToken, but can be any).

useFactory : Function

A function to invoke to create a value for this token. The function is invoked with resolved values of tokens in the deps field.

deps : any[]

A list of tokens which need to be resolved by the injector. The list of values is than used as arguments to the useFactory function.

multi : boolean

If true, than injector returns an array of instances. This is useful to allow multiple providers spread across many files to provide configuration information to a common token.

1
2
3
4
5
6
7
const injector = ReflectiveInjector.resolveAndCreate([
  {provide: 'local', multi: true, useValue: 'en'},
  {provide: 'local', multi: true, useValue: 'sk'},
]);
 
const locales: string[] = injector.get('local');
expect(locales).toEqual(['en', 'sk']);

exported from @angular/core/index, defined in @angular/core/src/di/provider.ts

doc_Angular
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.