【问题标题】:how to create a reusable component in angular with different service injection?如何使用不同的服务注入以角度创建可重用组件?
【发布时间】: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


【解决方案1】:

如果您要做的是根据您所在的位置以不同的方式提供服务,那么我将定义一个 SuperClass,该服务的不同实现将继承该超类。我们称它为 SuperClass,然后在组件中而不是 ConfirmService 中注入 SuperClass。接下来,您只需在不同的模块中以不同的方式提供它:

// module 1
{provide: SuperClass, useClass: ConfirmServiceImplementation}

// module 2
{provide: SuperClass, useClass: ConfirmServiceAnotherImplementation}

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 2018-11-23
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 2019-03-20
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多