
安装
npm install @decorators/di --save
示例
完整的工作示例可见于 实例 文件夹.
API 密码
@Injectable()- 登记集装箱内供应商类别
@Injectable()
class HttpService {}
@Inject(injectable: Injectable)- 将参数标为依赖性的参数装饰器.
@Injectable()
class HttpService {
constructor(@Inject(API_URL) apiUrl: string) {}
}
@Optional()- 将参数标为可选依赖性的参数装饰器.
@Injectable()
class HttpService {
constructor(@Optional() @Inject(API_URL) apiUrl: string) {}
}
InjectionToken- 创建一个可以在 DI 中用作提供方的符号.
const API_URL = new InjectionToken('API_URL');
...
@Injectable()
class HttpService {
constructor(@Inject(API_URL) apiUrl: string) {}
}
Container- 集装箱接口.setParent(container: Container)- 设置母容器.provide(providers: Providers[])- 登记一系列提供者..get<T>(injectable: Injectable): Promise<T>- 收回承诺 与注射的例子,扔:MissingProviderError如果找不到依赖提供者RecursiveProviderError在递归依赖性注射的情况下
const container = new Container();
container.provide([
{
provide: 'Message',
async useFactory() {
return delay('Async Provider');
},
},
{
provide: 'Hello World',
useClass: Service,
},
]);
多种支助
可以用一个注射符通过 multi 旗帜 :
container.provide([
{
provide: GLOBAL_PIPE,
useClass: ServerPipe,
multi: true
},
{
provide: GLOBAL_PIPE,
useClass: ErrorPipe,
multi: true
},
]);