Angular2 DI in Typescript. Can we use it in node.js / non-angular projects? Angular2 DI in Typescript. Can we use it in node.js / non-angular projects? angular angular

Angular2 DI in Typescript. Can we use it in node.js / non-angular projects?


Seems someone has extracted dependency injection from Angular2 recently(Jan 2017), which allow it to use outside of the framework.

https://github.com/mgechev/injection-js


As of Angular 2 RC.5, DI is a part of @angular/core package. For non-Angular uses, it was recently extracted into injection-js package by Minko Gechev, a member of Angular team.

Here is a short ES6, Node-friendly example:

// may not be needed for injection-js and recent @angular/core versions// if ES5-flavoured `Class` helper isn't usedrequire('reflect-metadata');const { Inject, Injector, ReflectiveInjector, OpaqueToken } = require('@angular/core');// or ... = require('injection-js');const bread = new OpaqueToken;const cutlet = new OpaqueToken;class Sandwich {    constructor(bread, cutlet, injector) {        const anotherBread = injector.get('bread');        injector === rootInjector;        bread === 'bread';        anotherBread === 'bread';        cutlet === 'cutlet';    }}Sandwich.parameters = [    new Inject(bread),    new Inject(cutlet),    new Inject(Injector)];const rootInjector = ReflectiveInjector.resolveAndCreate([    { provide: 'bread', useValue: 'bread' },    { provide: bread, useValue: 'bread' },    { provide: cutlet, useValue: 'cutlet' },    Sandwich]);const sandwich = rootInjector.get(Sandwich);


I doubt it, it doesn't look like it has been extracted into a component. It's a bit sad that major frameworks like Angular still have this monolithic approach, I would rather like to see Component oriented frameworks like Symfony, but JavaScript isn't quite there yet.

In the meantime you have InversifyJS that doesn't look bad.