A B*_*ife 7 dependency-injection typescript angular angular-dependency-injection
在@Input属性中注入“服务”依赖项是一个好习惯吗?此上下文中的服务不是在根级别管理的单例实例,而是接口不同实现的多个实例。
考虑以下示例:在 Angular 库中,ShapeComponent 依赖于 ShapeService(接口)。
成分
@Component({
selector: 'ex-shape',
templateUrl: '..',
})
export class ShapeComponent {
constructor(shapeServiceCtor: ShapeService)
@Input shapeServiceInput: ShapeService;
}
Run Code Online (Sandbox Code Playgroud)
解决依赖关系的一种简单方法是设置输入属性,如下面的代码所示。
<ex-shape [shapeServiceInput]="rectangleShapeService" />
<ex-shape [shapeServiceInput]="ellipseShapeService" />
<ex-shape [shapeServiceInput]="polygonShapeService" />
Run Code Online (Sandbox Code Playgroud)
上述方法是否适用于解决组件中的依赖关系?
如果使用输入属性方法,则服务/依赖项必须以相同的方式传播到子组件。这种方法的缺点是父组件必须接受所有依赖项作为输入属性。
是否有任何推荐的方法可以在库级别注入和作用域依赖项?
在这一点上,您并没有真正使用 Angular 的依赖注入,在您的情况下,我不确定这是好是坏。
如果 ShapeComponent 无法知道它正在使用的服务实例,并且每次调用它时都需要传递一个任意实例,这应该没问题。
如果 ShapeComponent 的父级将始终传递相同的服务实例,则父级可以将其包含在其providers数组中,然后子级 ShapeComponents 将使用相同的实例。
Angular 的文档有一些关于 DI 层次结构的更详细信息 https://angular.io/guide/hierarchical-dependency-injection
您对 的调用constructor(shapeServiceCtor: ShapeService)也会导致一些混乱,因为组件将同时注入一个 DI 和另一个(或可能相同的)实例来自@Input
| 归档时间: |
|
| 查看次数: |
1001 次 |
| 最近记录: |