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

前端 未结 6 899
孤独总比滥情好
孤独总比滥情好 2020-12-05 13:41

Was the angular2 dependency injection container designed for standalone use, and is it possible to use it for typescript/javascript server-side applications ?

I open

6条回答
  •  [愿得一人]
    2020-12-05 14:20

    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 used
    require('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);
    

提交回复
热议问题