小编Joã*_*ira的帖子

Angularjs 4 - 注入服务而不在构造函数上传递参数

有没有办法将服务注入到类中,而不必在构造函数上将其声明为参数?

通常的方式工作得很好,我没有抱怨。我只是想创建一个超类来处理一些女巫依赖于服务的东西,我希望它是独立的,我不想在子类上引用该服务。

这是通常的方式:

export class MyComponent {
  constructor(private someService: SomeNpmInstalledService) {}

  doSomething() {
    this.someService.do();
  }
}
Run Code Online (Sandbox Code Playgroud)

这就是我要找的:

export class MyComponent {
  @Some injection magic annotation here
  private someService: SomeNpmInstalledService;

  constructor() {}

  doSomething() {
    this.someService.do();
  }
}
Run Code Online (Sandbox Code Playgroud)

我将尝试通过以下示例来解释我想要这种功能的原因:

export class MyComponent extends MySuperClass {
  constructor() {
    super();
  }

  doSomething() {
    super.someSuperClassFonctionality(); 
  }
}

export class MySuperClass {
  constructor(private someService: SomeNpmInstalledService) {}

  someSuperClassFonctionality() {
    someService.doStuff(); 
  }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了一个错误,因为在我的组件中,当我调用super() 时,我必须传递在我的超类的构造函数上定义的参数。但这正是我不想做的。我希望我的组件甚至不知道超类中使用的服务。

dependency-injection angular

6
推荐指数
1
解决办法
2881
查看次数

标签 统计

angular ×1

dependency-injection ×1