Injectable¶
There are two ways to create an injectable: either be using the
Injectable()
decorator, or by calling provide()
. A provider
can be used to resolve an instance using one of a few options. By using the
Injectable decorator, the DI framework will automatically choose the
useConstructor option. If you need more flexibility, you can use provide.
-
Injectable
(injectableInfo)¶ Creates an Injectable decorator.
Arguments: - injectableInfo (InjectableTableEntry) – Injectable information that specifies how the DI framework should create an instance and the lifetime of that instance.
Returns: (Anonymous function) – The decorator used to designate a class an injectable resolution. The decorator will automatically create a
useClass
provider. The provider will use the class’ name in camelCase for resolving.
Important
In order to be recognized by the context, it must be included in
ContextInitialization.providers
.
-
provide
(name, injectableInfo)¶ Manually provide an injectable.
Arguments: - name (string) – the name that will be used to resolve the injectable.
- injectableInfo (InjectableTableEntry) – Injectable information that specifies how the DI framework should create an instance and the lifetime of that instance.
Returns: string – the name.
-
class
InjectableTableEntry
(T)¶ interface, exported from
ommander-mv
Meta information for an Injectable.
Arguments: - T – The type being being provided.
-
InjectableTableEntry.
lifetime
¶ type: LifetimeType
Either
SINGLETON
orTRANSIENT
. In the former, only one instance will be resolved and cached for future resolves. In the latter, a new instance will be created each time it is resolved. Note this only affects auseConstructor
provider.
-
InjectableTableEntry.
provider
¶ type: Provider
Describes how the DI framework should create an instance during resolution.
-
class
Provider
(T)¶ interface, exported from
ommander-mv
Describes how the DI framework should create an instance during resolution. Only one of the options should be used. The behavior is not well-defined if more than one is used and can change in a future release.
Arguments: - T – The type being provided
-
Provider.
useConstructor
¶ type: Constructor
The class given will be created and resolved using
new
.
-
Provider.
useFactory
¶ type: AnyFunction
The factory function given will be called, and the return value will be resolved. Dependencies can be injected into the function’s parameters just like constructor injection.
-
Provider.
useValue
¶ type: any
The value given will be resolved as is.
Example¶
1 2 3 4 5 6 7 8 9 10 11 12 | @Injectable({
lifetime: Lifetime.SINGLETON
})
export class MyService {
constructor ({ apiUrl }) {
this.apiUrl = apiUrl
}
}
provide('apiUrl', {
useValue: 'api.site.com/v1/'
})
|
As you can see, injectables themselves can inject other injectables. The example also shows a custom provider.