angular - Angular:在没有@Injectable 装饰器的情况下注入类
问题描述
我有一些来自图书馆的课程,例如:
class Foo {
// ...
}
class Bar {
constructor(private foo: Foo) { }
// ...
}
这些类没有@Injectable
装饰器,因为库不是 Angular 特定的。但是,我想在我的应用程序中将它们用作服务。
到目前为止,我的解决方案是创建派生类,例如:
@Injectable()
class InjectableFoo extend Foo {
constructor() { super(); }
}
@Injectable()
class InjectableBar extends Bar {
constructor(foo: InjectableFoo) {
super(foo);
}
}
我对这个解决方案不是很兴奋,因为它需要额外的样板代码,没有增加任何实际价值,并且在组件中使用这些服务的人必须知道使用“可注入”版本而不是(更简单的)基础类。在一个完美的世界里,我希望能够告诉 AngularFoo
并且Bar
应该是可注入的。
这可能吗?
解决方案
您可以在NgModule
使用工厂提供者和价值提供者时提供它们。
https://angular.io/api/core/FactoryProvider
https://angular.io/api/core/ValueProvider
class Foo {
// ...
}
class Bar {
constructor(private foo: Foo) { }
// ...
}
@NgModule({
providers: [
{provide: Foo, useValue: new Foo()},
{provide: Bar, useFactory: (foo) => new Bar(foo), deps: [Foo]}
]
});
在上面的示例中,您可以使用useValue: new Foo()
,但这里的关键是deps: [Foo]
允许您注入foo
工厂函数,Bar
因为它是一个依赖项。
稍后在组件中,您可以执行以下操作。
@Component({...})
export class MyComponent {
constructor(foo: Foo, bar: Bar) { }
}
推荐阅读
- r - ggplot2 绘图无法识别上课日期
- python - Django 尝试点赞帖子时,值正在发生变化,但在 /something/something/ 处也会出现错误 NoReverseMatch
- sql - SQL Server 中的问号
- c# - 统一,如何在脚本中访问 EventSystem 调试信息
- windows - 在默认浏览器中打开 HTML 文件,而不是在 Windows 批处理文件中打开文本编辑器
- java - 使用 GSON 解析 json 字符串列表
- java - 在 Linux 上采用 OpenJDK11 选择
- c++ - 生成字符串束的标识号
- java - 如何在另一个类中获取java类的值
- typescript - 用模拟的打字稿类开玩笑“mock.calls”为空