angular - 如何避免在多个组件中注入相同的依赖项
问题描述
我正在为我的应用程序使用 Angular 7。我在构造函数(---)的多个组件中注入相同的依赖项。我可以在超类/组件中注入一些并重用它吗?..如果有人知道最佳解决方案,请告诉我。
提前致谢
解决方案
If it's always the same injections, you can use an abstract component and use Injector
.
export abstract class BaseComponent {
protected myService1: MyService1;
protected myService2: MyService2;
protected myService3: MyService3;
constructor(@Inject(Injector)public injector: Injector) {
this.myService1 = injector.get(MyService1);
this.myService2 = injector.get(MyService2);
this.myService3 = injector.get(MyService3);
}
}
@Inject
allow you to not have constructor on childs.
And have childs:
export class MyComponent extends BaseComponent {
constructor(public injector: Injector) {
super(injector);
}
...
}
or
export class MyComponent extends BaseComponent {
...
}
推荐阅读
- javascript - Highcharts 延迟构建工具提示
- python - 使用多处理时函数返回奇怪的输出
- javascript - 为什么时刻 js 给出不同的毫秒数?
- node.js - 为什么我的 lambda 仅在我用一些消息进行回调时才起作用?
- php - PROD 部署后 PHP 删除 Phing
- angular - 如何在角度 4 中为自定义排序管道编写单元测试用例?
- azure-functions - 天蓝色函数输入绑定到天蓝色事件中心时 EventData 数组的大小
- ios - AVFoundation 能否使用 iPhone XR 后置摄像头捕捉深度?
- javascript - OAuth2 和微服务:创建用户
- android - firebase 将子级添加到不存在的父级