【发布时间】:2020-04-27 12:06:51
【问题描述】:
更新
简介
在 Angular 中使用装饰器 @Injectable 提供服务。
@Injectable() // -> works
export class MyService {
constructor() {}
}
抽象@Injectable
在 Ivy 之前,可以为 @Injectable 构建抽象(例如,用于动态配置提供程序、增强服务类)。
以下 sn-p 显示了如何包装 @Injectable 的示例。
function InjectableEnhanced() {
return <T extends new (...args: any[]) => InstanceType<T>>(target: T) => {
Injectable({ providedIn: "root" })(target);
};
}
在启用 Ivy 时,使用装饰器 InjectableEnhanced(见上文)不起作用。
以下代码被截断会导致运行时错误。
@InjectableEnhanced() // -> does not work
export class MyService {
constructor() {}
}
运行时错误
使用 @InjectableEnhanced 和 angular/cli 编译服务有效,但浏览器中显示以下错误。对应的项目可以在https://github.com/GregOnNet/ng-9-inject.git找到。
也许,Angular 编译器做了一些代码转换,但不能再在其他装饰器中解析 @Injectable。
查看 Angular 存储库,可以在 injectable.ts 中找到对 JIT 编译器的引用(请参阅:https://github.com/angular/angular/blob/master/packages/core/src/di/injectable.ts#L14)。
问题
还有没有办法抽象出@Injectable?
复制库
【问题讨论】:
标签: angular typescript decorator angular-ivy