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

Joã*_*ira 6 dependency-injection angular

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

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

这是通常的方式:

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() 时,我必须传递在我的超类的构造函数上定义的参数。但这正是我不想做的。我希望我的组件甚至不知道超类中使用的服务。

hay*_*rse 1

是:使用注射器。 https://angular.io/api/core/Injector

import { Injector } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

然后在你的构造函数中:

constructor(injector: Injector) {
  let this.service = injector.get(ServiceToInject);
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的重播。这几乎是我所需要的,但是在构造函数中使用注入器仍然是我需要的一个问题。我编辑了原来的问题以添加更多细节。 (4认同)