【问题标题】:How can I add dependency to the current class using AngularJs and TypeScript?如何使用 AngularJs 和 TypeScript 向当前类添加依赖项?
【发布时间】:2018-02-13 03:20:16
【问题描述】:

假设我有一个组件类如下;

@Component({
  selector: "my",
  templateUrl: "/app/my.html"
})
export class MyComponent extends MyBase {
  helper: Helper;
  constructor() 
  { 
     helper = new Helper(this);
  } 
}

Helper 类位于另一个类似的文件中。

export class Helper {
    constructor(protected component: MyBase)
    {

    }
}

看起来我无论如何都不能对我的助手类使用依赖注入,因为它存储了对组件的引用。我认为完成这项工作的唯一方法是保持原样或在注入后设置组件实例,如下所示,我也不喜欢。

export class MyComponent extends MyBase {
  constructor(public helper:Helper) 
  { 
    helper.component = this;
  } 
}

Helper 类位于另一个类似的文件中。

@Injectable()
export class Helper {
    public component : MyBase;
}

这两个都感觉不对,但我没有看到合理的选择。

【问题讨论】:

    标签: angularjs typescript dependency-injection


    【解决方案1】:

    我认为在这种情况下最好的方法可能是消除依赖类实例。

    帮助类的真正实现实际上是这样的:

    export abstract class MvcAction<TComponent>
    {
      constructor(protected component:TComponent)
      public abstract complete(): void;
    }
    

    子类如下所示:

    export class CustomAction extends MvcAction<TComponent>
    {
      constructor(protected component:TComponent)
      {
          super(component);
      }
      public abstract complete(): void;
    }
    

    并且基础组件类根据需要调用方法:

    public perform(action: MvcAction<T>) {
        action.complete();
    }
    

    因此,现在在实例中调用动作传递似乎更实际,这将消除对构造函数的依赖,新实现如下所示。

    export abstract class MvcAction<ComponentBase>
    {
      public abstract complete(component: ComponentBase): void;
    }
    

    子类现在看起来像这样:

    export class CustomAction extends MvcAction<TComponent>
    {
      public complete(component: TComponent): void
      {
          // Do something with the component.
      }
    }
    

    并且组件基类根据需要调用方法。

    public perform(action: MvcAction<ComponentBase>) {
        action.complete(this);
    }
    

    我的组件现在可以在没有不需要的实例依赖的情况下正常使用依赖注入,如下所示:

    export class SomeComponent extends ComponentBase<any> {
      constructor(protected customAction: CustomAction ) {
      }
    }
    

    而模板代码是这样的:

    <a (click)="perform(customAction)">Do Custom Action</a>
    

    【讨论】:

      猜你喜欢
      • 2019-01-30
      • 2013-11-03
      • 2016-10-06
      • 2018-05-27
      • 2015-01-10
      • 2017-03-07
      • 2018-05-09
      • 2014-09-21
      • 1970-01-01
      相关资源
      最近更新 更多