【发布时间】:2019-06-09 10:12:47
【问题描述】:
他们说组件应该是可重复使用的,但我不知道如何让我的机箱可重复使用? 我想要一个用于在服务器上确认某事的组件?
@Component({
selector: 'app-confirm',
template: '<button (Click)="confirm()">'
})
export class ConfirmComponent {
constructor(private confirmService: ConfirmService){}
confirm(){
this.confirmService.confirm();
}
}
现在,如果我想在其他地方使用它,如何更改注入到此类的确认服务类,但随后为每个组件创建此服务?
编辑
当我自己处理依赖注入时,我会这样做:
class ConfirmComponent{
confirmService: ConfirmServiceInterface;
constructor(confirmService: ConfirmServiceInterface){
this.confirmService = confirmService;
}
}
第一次使用:
new ConfirmComponent(a);
第二次使用:
new ConfirmComponent(b);
我想知道如何在 Angular 中做到这一点?
【问题讨论】:
-
要使其“可重用”,您必须覆盖提供程序。 It's all in the documentation。您可以在组件级别、模块级别执行此操作,甚至可以使其动态化。
-
我在我的应用程序的某个地方使用它,如果我想在其他地方使用不同的服务重用它,我应该如何提供它,所以它知道这里使用这个,那里使用那个
-
最干净的方法是在模块级别使用工厂或覆盖。我给了你一个链接,你可以随时查看,看看什么最适合你
标签: angular dependency-injection angular-components reusability