【发布时间】:2018-06-25 16:07:31
【问题描述】:
我在问自己,父/子组件中的@Input/@Output 和 使用仅通过依赖注入@Injectable() 启用一次的服务之间的区别在哪里。或者除了 Input/Output 只能在 parent-/child-comp 中使用之外还有什么区别。
以下示例以获得更好的可视化:
使用@Input:
<parent-comp>
<child-comp [inputFromParent]="valueFromParent"></child-comp>
</parent-comp>
子组件:
@Component({
selector: 'child-comp',
template: ...
})
export class ChildComponent {
@Input() public inputFromParent: string;
}
依赖注入
@Injectable()
export class Service {
private value: string;
public get value(): string {
return value;
}
public set value(input): void {
value = input;
}
}
现在我们可以在父组件中设置值。并通过依赖注入获取子组件中的值。 子组件:
@Component({
selector: 'child-comp',
template: ...
})
export class ChildComponent {
private value: string;
constructor(private service: Service) {
this.value = this.service.getValue;
}
}
尽管第一种方法看起来更简单,但我认识到使用 3-4 个属性通过父/子组合进行。使用@Input/@Output 会使 tamplete 变得非常混乱和笨拙。
【问题讨论】:
-
使用服务更加灵活,因为它使用@Injectable() 装饰器创建服务的单例实例,并且可以将其注入任何组件中,甚至可以注入到另一个服务中。
-
我倾向于避免为了灵活性而牺牲正确性。
标签: angular typescript design-patterns dependency-injection