问题描述
是否将角度2依赖注入容器设计为独立使用,是否可以将其用于typescript / javascript服务器端应用程序?我打开了一个问题10月16日()在di项目,我猜应该把它变成v2。显然这是不可能的。什么是新的angular2 di?我可以用独立的方式使用js / es6 / ts项目吗?
从角度2 RC.5起,DI是 @ angular / core
包的一部分。对于非角色使用,最近由Angular团队的成员Minko Gechev将其提取到 injection-js
包中。
这是一个简短的ES6,友好的例子:
//可能不需要注入js和近期@ angular / core版本
//如果没有使用ES5风格的`Class`帮助器
require('reflect-metadata');
const {Inject,Injector,ReflectiveInjector,OpaqueToken} = require('@ angular / core');
//或... = require('inject-js');
const bread = new OpaqueToken;
const cutlet = new OpaqueToken;
class三明治{
构造函数(bread,cutlet,inject){
const anotherBread = inject.get('bread');
注射器=== rootInjector;
bread ==='bread';
anotherBread ==='bread';
cutlet ==='cutlet';
}
}
Sandwich.parameters = [
new Inject(bread),
new Inject(cutlet),
new Inject注射器)
];
const rootInjector = ReflectiveInjector.resolveAndCreate([
{provide:'bread',useValue:'bread'},
{provide:bread,useValue:'bread'},
{提供:cutlet,useValue:'cutlet'},
三明治
]);
const sandwich = rootInjector.get(Sandwich);
Was the angular2 dependency injection container designed for standalone use, and is it possible to use it for typescript/javascript server-side applications ?
I opened an issue on Oct. 16 (https://github.com/angular/di.js/issues/108) on the di project which was I guess supposed to make it into v2. Apparently this was not possible. What's up with the new angular2 di ? Can I use it in a standalone fashion with js / es6 / ts projects?
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);
这篇关于Angular2 DI在Typescript。我们可以在node.js /非角度项目中使用它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!