injection-js
- Version 2.4.0
- Published
- 324 kB
- 1 dependency
- MIT license
Install
npm i injection-js
yarn add injection-js
pnpm add injection-js
Overview
Dependency Injection library for JavaScript and TypeScript
Index
Variables
Functions
Classes
Interfaces
Type Aliases
Variables
variable Host
const Host: HostDecorator;
Host decorator and metadata.
variable Inject
const Inject: InjectDecorator;
Inject decorator and metadata.
variable Injectable
const Injectable: InjectableDecorator;
Injectable decorator and metadata.
variable Optional
const Optional: OptionalDecorator;
Optional decorator and metadata.
variable Self
const Self: SelfDecorator;
Self decorator and metadata.
variable SkipSelf
const SkipSelf: SkipSelfDecorator;
SkipSelf decorator and metadata.
variable Type
const Type: FunctionConstructor;
Represents a type that a Component or other object is instances of.
An example of a
Type
isMyCustomComponent
class, which in JavaScript is be represented by theMyCustomComponent
constructor function.
Functions
function Class
Class: (this: any, clsDef: ClassDefinition) => Type<any>;
Provides a way for expressing ES6 classes with parameter annotations in ES5.
## Basic Example
var Greeter = ng.Class({constructor: function(name) {this.name = name;},greet: function() {alert('Hello ' + this.name + '!');}});is equivalent to ES6:
class Greeter {constructor(name) {this.name = name;}greet() {alert('Hello ' + this.name + '!');}}or equivalent to ES5:
var Greeter = function (name) {this.name = name;}Greeter.prototype.greet = function () {alert('Hello ' + this.name + '!');}### Example with parameter annotations
var MyService = ng.Class({constructor: [String, [new Optional(), Service], function(name, myService) {...}]});is equivalent to ES6:
class MyService {constructor(name: string, @Optional() myService: Service) {...}}### Example with inheritance
var Shape = ng.Class({constructor: (color) {this.color = color;}});var Square = ng.Class({extends: Shape,constructor: function(color, size) {Shape.call(this, color);this.size = size;}});{globalThis}
function forwardRef
forwardRef: (forwardRefFn: ForwardRefFn) => Type<any>;
Allows to refer to references which are not yet defined.
For instance,
forwardRef
is used when thetoken
which we need to refer to for the purposes of DI is declared, but not yet defined. It is also used when thetoken
which we use when creating a query is not yet defined.### Example
Modifiers
@experimental
function isType
isType: (v: any) => v is Type<any>;
function makeDecorator
makeDecorator: ( name: string, props: { [name: string]: any }, parentClass?: any, chainFn?: (fn: Function) => void) => (...args: any[]) => (cls: any) => any;
{globalThis}
function makeParamDecorator
makeParamDecorator: ( name: string, props: ([string, any] | { [name: string]: any })[], parentClass?: any) => any;
function makePropDecorator
makePropDecorator: ( name: string, props: ([string, any] | { [key: string]: any })[], parentClass?: any) => any;
function resolveDependencies
resolveDependencies: (...inputs: Constructor[]) => Constructor[];
This utility function receives a spread of injectable classes and returns an array of all their dependencies. Also resolves optional dependencies.
### Important:
Dynamically resolving dependencies using this function will not play nice with static analysis tools, including tree-shaking. From a static analysis perspective, any dependencies which are only resolved using this function will look as though they are not used (and will be removed by tree-shaking). This *severely* limits the usefulness of this function.
### Example:
class HTTP {}class Database {}// commenting out the decorator because the `@` symbol is spoiling// jsDoc rendering in vscode// @Injectable()class PersonService {constructor(private http: HTTP,private database: Database,) {}}// @Injectable()class OrganizationService {constructor(private http: HTTP,private personService: PersonService,) {}}const injector = ReflectiveInjector.resolveAndCreate(resolveDependencies(OrganizationService));const organizationService = injector.get(OrganizationService);
function resolveForwardRef
resolveForwardRef: (type: any) => any;
Lazily retrieves the reference value from a forwardRef.
Acts as the identity function when given a non-forward-ref value.
### Example ([live demo](http://plnkr.co/edit/GU72mJrk1fiodChcmiDR?p=preview))
See: forwardRef
Modifiers
@experimental
Classes
class InjectionToken
class InjectionToken<T> extends OpaqueToken {}
Creates a token that can be used in a DI Provider.
Use an
InjectionToken
whenever the type you are injecting is not reified (does not have a runtime representation) such as when injecting an interface, callable type, array or parametrized type.InjectionToken
is parameterized onT
which is the type of object which will be returned by theInjector
. This provides additional level of type safety.interface MyInterface {...}var myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken'));// myInterface is inferred to be MyInterface.### Example
constructor
constructor(desc: string);
method toString
toString: () => string;
class Injector
abstract class Injector {}
Injector interface
const injector: Injector = ...;injector.get(...);For more details, see the .
### Example
Injector
returns itself when givenInjector
as a token:
property NULL
static NULL: Injector;
property THROW_IF_NOT_FOUND
static THROW_IF_NOT_FOUND: Object;
method get
abstract get: { <T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T): T; (token: any, notFoundValue?: any): any;};
Retrieves an instance from the injector based on the provided token. If not found: - Throws NoProviderError if no
notFoundValue
that is not equal to Injector.THROW_IF_NOT_FOUND is given - Returns thenotFoundValue
otherwiseDeprecated
from v4.0.0 use Type or InjectionToken {duplicate}
class OpaqueToken
class OpaqueToken {}
Creates a token that can be used in a DI Provider.
### Example ([live demo](http://plnkr.co/edit/Ys9ezXpj2Mnoy3Uc8KBp?p=preview))
var t = new OpaqueToken("value");var injector = Injector.resolveAndCreate([{provide: t, useValue: "bindingValue"}]);expect(injector.get(t)).toEqual("bindingValue");Using an
OpaqueToken
is preferable to using strings as tokens because of possible collisions caused by multiple providers using the same string as two different tokens.Using an
OpaqueToken
is preferable to using anObject
as tokens because it provides better error messages.Deprecated
since v4.0.0 because it does not support type information, use
InjectionToken<?>
instead.
constructor
constructor(_desc: string);
method toString
toString: () => string;
class ReflectiveInjector
abstract class ReflectiveInjector implements Injector {}
A ReflectiveDependency injection container used for instantiating objects and resolving dependencies.
An
Injector
is a replacement for anew
operator, which can automatically resolve the constructor dependencies.In typical use, application code asks for the dependencies in the constructor and they are resolved by the
Injector
.### Example ([live demo](http://plnkr.co/edit/jzjec0?p=preview))
The following example creates an
Injector
configured to createEngine
andCar
.@Injectable()class Engine {}@Injectable()class Car {constructor(public engine:Engine) {}}var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);var car = injector.get(Car);expect(car instanceof Car).toBe(true);expect(car.engine instanceof Engine).toBe(true);Notice, we don't use the
new
operator because we explicitly want to have theInjector
resolve all of the object's dependencies automatically.
property parent
readonly parent: Injector;
Parent of this injector.
<!-- TODO: Add a link to the section of the user guide talking about hierarchical injection. -->
### Example ([live demo](http://plnkr.co/edit/eosMGo?p=preview))
var parent = ReflectiveInjector.resolveAndCreate([]);var child = parent.resolveAndCreateChild([]);expect(child.parent).toBe(parent);
method createChildFromResolved
abstract createChildFromResolved: ( providers: ResolvedReflectiveProvider[]) => ReflectiveInjector;
Creates a child injector from previously resolved providers.
<!-- TODO: Add a link to the section of the user guide talking about hierarchical injection. -->
This API is the recommended way to construct injectors in performance-sensitive parts.
### Example ([live demo](http://plnkr.co/edit/VhyfjN?p=preview))
class ParentProvider {}class ChildProvider {}var parentProviders = ReflectiveInjector.resolve([ParentProvider]);var childProviders = ReflectiveInjector.resolve([ChildProvider]);var parent = ReflectiveInjector.fromResolvedProviders(parentProviders);var child = parent.createChildFromResolved(childProviders);expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
method fromResolvedProviders
static fromResolvedProviders: ( providers: ResolvedReflectiveProvider[], parent?: Injector) => ReflectiveInjector;
Creates an injector from previously resolved providers.
This API is the recommended way to construct injectors in performance-sensitive parts.
### Example ([live demo](http://plnkr.co/edit/KrSMci?p=preview))
@Injectable()class Engine {}@Injectable()class Car {constructor(public engine:Engine) {}}var providers = ReflectiveInjector.resolve([Car, Engine]);var injector = ReflectiveInjector.fromResolvedProviders(providers);expect(injector.get(Car) instanceof Car).toBe(true);Modifiers
@experimental
method get
abstract get: (token: any, notFoundValue?: any) => any;
method instantiateResolved
abstract instantiateResolved: (provider: ResolvedReflectiveProvider) => any;
Instantiates an object using a resolved provider in the context of the injector.
The created object does not get cached by the injector.
### Example ([live demo](http://plnkr.co/edit/ptCImQ?p=preview))
@Injectable()class Engine {}@Injectable()class Car {constructor(public engine:Engine) {}}var injector = ReflectiveInjector.resolveAndCreate([Engine]);var carProvider = ReflectiveInjector.resolve([Car])[0];var car = injector.instantiateResolved(carProvider);expect(car.engine).toBe(injector.get(Engine));expect(car).not.toBe(injector.instantiateResolved(carProvider));
method resolve
static resolve: (providers: Provider[]) => ResolvedReflectiveProvider[];
Turns an array of provider definitions into an array of resolved providers.
A resolution is a process of flattening multiple nested arrays and converting individual providers into an array of ResolvedReflectiveProviders.
### Example ([live demo](http://plnkr.co/edit/AiXTHi?p=preview))
@Injectable()class Engine {}@Injectable()class Car {constructor(public engine:Engine) {}}var providers = ReflectiveInjector.resolve([Car, [[Engine]]]);expect(providers.length).toEqual(2);expect(providers[0] instanceof ResolvedReflectiveProvider).toBe(true);expect(providers[0].key.displayName).toBe("Car");expect(providers[0].dependencies.length).toEqual(1);expect(providers[0].factory).toBeDefined();expect(providers[1].key.displayName).toBe("Engine");});See ReflectiveInjector#fromResolvedProviders for more info.
method resolveAndCreate
static resolveAndCreate: ( providers: Provider[], parent?: Injector) => ReflectiveInjector;
Resolves an array of providers and creates an injector from those providers.
The passed-in providers can be an array of
Type
, Provider, or a recursive array of more providers.### Example ([live demo](http://plnkr.co/edit/ePOccA?p=preview))
@Injectable()class Engine {}@Injectable()class Car {constructor(public engine:Engine) {}}var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);expect(injector.get(Car) instanceof Car).toBe(true);This function is slower than the corresponding
fromResolvedProviders
because it needs to resolve the passed-in providers first. See Injector#resolve and Injector#fromResolvedProviders.
method resolveAndCreateChild
abstract resolveAndCreateChild: (providers: Provider[]) => ReflectiveInjector;
Resolves an array of providers and creates a child injector from those providers.
<!-- TODO: Add a link to the section of the user guide talking about hierarchical injection. -->
The passed-in providers can be an array of
Type
, Provider, or a recursive array of more providers.### Example ([live demo](http://plnkr.co/edit/opB3T4?p=preview))
class ParentProvider {}class ChildProvider {}var parent = ReflectiveInjector.resolveAndCreate([ParentProvider]);var child = parent.resolveAndCreateChild([ChildProvider]);expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));This function is slower than the corresponding
createChildFromResolved
because it needs to resolve the passed-in providers first. See Injector#resolve and Injector#createChildFromResolved.
method resolveAndInstantiate
abstract resolveAndInstantiate: (provider: Provider) => any;
Resolves a provider and instantiates an object in the context of the injector.
The created object does not get cached by the injector.
### Example ([live demo](http://plnkr.co/edit/yvVXoB?p=preview))
@Injectable()class Engine {}@Injectable()class Car {constructor(public engine:Engine) {}}var injector = ReflectiveInjector.resolveAndCreate([Engine]);var car = injector.resolveAndInstantiate(Car);expect(car.engine).toBe(injector.get(Engine));expect(car).not.toBe(injector.resolveAndInstantiate(Car));
class ReflectiveKey
class ReflectiveKey {}
A unique object used for retrieving items from the ReflectiveInjector.
Keys have: - a system-wide unique
id
. - atoken
.Key
is used internally by ReflectiveInjector because its system-wide uniqueid
allows the injector to store created objects in a more efficient way.Key
should not be created directly. ReflectiveInjector creates keys automatically when resolving providers.Modifiers
@experimental
constructor
constructor(token: Object, id: number);
Private
property displayName
readonly displayName: string;
Returns a stringified token.
property id
id: number;
property numberOfKeys
static readonly numberOfKeys: number;
Returns
the number of keys registered in the system.
property token
token: Object;
method get
static get: (token: Object) => ReflectiveKey;
Retrieves a
Key
for a token.
class ResolvedReflectiveFactory
class ResolvedReflectiveFactory {}
An internal resolved representation of a factory function created by resolving Provider.
Modifiers
@experimental
constructor
constructor(factory: Function, dependencies: ReflectiveDependency[]);
property dependencies
dependencies: ReflectiveDependency[];
Arguments (dependencies) to the
factory
function.
property factory
factory: Function;
Factory function which can return an instance of an object represented by a key.
Interfaces
interface ClassProvider
interface ClassProvider {}
Configures the Injector to return an instance of
useClass
for a token.@Injectable()class MyService {}const provider: ClassProvider = {provide: 'someToken', useClass: MyService};For more details, see the .
### Example
Note that following two providers are not equal:
property multi
multi?: boolean;
If true, then 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.
### Example
property provide
provide: any;
An injection token. (Typically an instance of
Type
orInjectionToken
, but can beany
).
property useClass
useClass: Type<any>;
Class to instantiate for the
token
.
interface ExistingProvider
interface ExistingProvider {}
Configures the Injector to return a value of another
useExisting
token.const provider: ExistingProvider = {provide: 'someToken', useExisting: 'someOtherToken'};For more details, see the .
### Example
property multi
multi?: boolean;
If true, then 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.
### Example
property provide
provide: any;
An injection token. (Typically an instance of
Type
orInjectionToken
, but can beany
).
property useExisting
useExisting: any;
Existing
token
to return. (equivalent toinjector.get(useExisting)
)
interface FactoryProvider
interface FactoryProvider {}
Configures the Injector to return a value by invoking a
useFactory
function.function serviceFactory() { ... }const provider: FactoryProvider = {provide: 'someToken', useFactory: serviceFactory, deps: []};For more details, see the .
### Example
Dependencies can also be marked as optional:
property deps
deps?: any[];
A list of
token
s which need to be resolved by the injector. The list of values is then used as arguments to theuseFactory
function.
property multi
multi?: boolean;
If true, then 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.
### Example
property provide
provide: any;
An injection token. (Typically an instance of
Type
orInjectionToken
, but can beany
).
property useFactory
useFactory: Function;
A function to invoke to create a value for this
token
. The function is invoked with resolved values oftoken
s in thedeps
field.
interface ForwardRefFn
interface ForwardRefFn {}
An interface that a function passed into forwardRef has to implement.
### Example
Modifiers
@experimental
call signature
(): any;
interface Host
interface Host {}
Type of the Host metadata.
interface HostDecorator
interface HostDecorator {}
Type of the Host decorator / constructor function.
construct signature
new (): Host;
call signature
(): any;
Specifies that an injector should retrieve a dependency from any injector until reaching the host element of the current component.
@Injectable()class Car {constructor(@Host() public engine:Engine) {}}For more details, see the .
### Example
interface Injectable
interface Injectable {}
Type of the Injectable metadata.
interface InjectableDecorator
interface InjectableDecorator {}
Type of the Injectable decorator / constructor function.
construct signature
new (): Injectable;
call signature
(): any;
A marker metadata that marks a class as available to Injector for creation.
@Injectable()class Car {}For more details, see the .
### Example
Injector will throw NoAnnotationError when trying to instantiate a class that does not have
@Injectable
marker, as shown in the example below.
interface InjectDecorator
interface InjectDecorator {}
Type of the Inject decorator / constructor function.
construct signature
new (token: any): Inject;
call signature
(token: any): any;
A parameter decorator that specifies a dependency.
@Injectable()class Car {constructor(@Inject("MyEngine") public engine:Engine) {}}For more details, see the .
### Example
When
@Inject()
is not present, Injector will use the type annotation of the parameter.### Example
interface Optional
interface Optional {}
Type of the Optional metadata.
interface OptionalDecorator
interface OptionalDecorator {}
Type of the Optional decorator / constructor function.
construct signature
new (): Optional;
call signature
(): any;
A parameter metadata that marks a dependency as optional. Injector provides
null
if the dependency is not found.@Injectable()class Car {constructor(@Optional() public engine:Engine) {}}For more details, see the .
### Example
interface ResolvedReflectiveProvider
interface ResolvedReflectiveProvider {}
An internal resolved representation of a Provider used by the Injector.
It is usually created automatically by
Injector.resolveAndCreate
.It can be created manually, as follows:
### Example ([live demo](http://plnkr.co/edit/RfEnhh8kUEI0G3qsnIeT?p%3Dpreview&p=preview))
var resolvedProviders = Injector.resolve([{ provide: 'message', useValue: 'Hello' }]);var injector = Injector.fromResolvedProviders(resolvedProviders);expect(injector.get('message')).toEqual('Hello');Modifiers
@experimental
property key
key: ReflectiveKey;
A key, usually a
Type<any>
.
property multiProvider
multiProvider: boolean;
Indicates if the provider is a multi-provider or a regular provider.
property resolvedFactories
resolvedFactories: ResolvedReflectiveFactory[];
Factory function which can return an instance of an object represented by a key.
interface Self
interface Self {}
Type of the Self metadata.
interface SelfDecorator
interface SelfDecorator {}
Type of the Self decorator / constructor function.
construct signature
new (): Self;
call signature
(): any;
Specifies that an Injector should retrieve a dependency only from itself.
@Injectable()class Car {constructor(@Self() public engine:Engine) {}}For more details, see the .
### Example
interface SkipSelf
interface SkipSelf {}
Type of the SkipSelf metadata.
interface SkipSelfDecorator
interface SkipSelfDecorator {}
Type of the SkipSelf decorator / constructor function.
construct signature
new (): SkipSelf;
call signature
(): any;
Specifies that the dependency resolution should start from the parent injector.
@Injectable()class Car {constructor(@SkipSelf() public engine:Engine) {}}For more details, see the .
### Example
interface Type
interface Type<T = object> extends Function {}
construct signature
new (...args: any[]): T;
interface TypeDecorator
interface TypeDecorator {}
An interface implemented by all Angular type decorators, which allows them to be used as ES7 decorators as well as Angular DSL syntax.
DSL syntax:
var MyClass = ng.Component({...}).Class({...});ES7 syntax:
@ng.Component({...})class MyClass {...}
property annotations
annotations: any[];
Storage for the accumulated annotations so far used by the DSL syntax.
Used by Class to annotate the generated class.
method Class
Class: (obj: ClassDefinition) => Type<any>;
Generate a class from the definition and annotate it with TypeDecorator#annotations.
call signature
<T extends Type<any>>(type: T): T;
Invoke as ES7 decorator.
call signature
(target: Object, propertyKey?: string | symbol, parameterIndex?: number): void;
interface TypeProvider
interface TypeProvider extends Type<any> {}
Configures the Injector to return an instance of
Type
when `Type' is used as token.@Injectable()class MyService {}const provider: TypeProvider = MyService;Create an instance by invoking the
new
operator and supplying additional arguments. This form is a short form ofTypeProvider
;For more details, see the .
### Example
interface ValueProvider
interface ValueProvider {}
Configures the Injector to return a value for a token.
const provider: ValueProvider = {provide: 'someToken', useValue: 'someValue'};For more details, see the .
### Example
property multi
multi?: boolean;
If true, then 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.
### Example
property provide
provide: any;
An injection token. (Typically an instance of
Type
orInjectionToken
, but can beany
).
property useValue
useValue: any;
The value to inject.
Type Aliases
type Provider
type Provider = | TypeProvider | ValueProvider | ClassProvider | ExistingProvider | FactoryProvider | any[];
Describes how the Injector should be configured. See TypeProvider, ValueProvider, ClassProvider, ExistingProvider, FactoryProvider.
For more details, see the .
Package Files (12)
Dependencies (1)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/injection-js
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/injection-js)
- HTML<a href="https://www.jsdocs.io/package/injection-js"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 2103 ms. - Missing or incorrect documentation? Open an issue for this package.