如何通过操作在 Angular 2 服务中注入提供者?

How to inject a provider in Angular 2 service from action?

我正在尝试在 Redux 的帮助下移除组件对 Angular 中服务的依赖。

基本上,流程是组件 -> 操作 -> 服务

服务中我想使用@angular/core的http模块,建议在构造函数中传入:

export class SampleService {
    constructor(public http: Http) {}
}

当我从操作中调用服务时,它不会获取 http 提供程序,因为我在其中没有 http 提供程序的实例。

export default class SampleAction {
    private _projectService;
    constructor() {
        this._sampleService = new SampleService();
    }
}

如何将 http 提供程序注入服务?

其实你不需要自己实例化服务。只需将服务注入组件或其他服务即可。重要的是为这个执行流程配置提供者。在您的情况下,Http(更普遍的是 HTTP_PROVIDERS)和 SampleSampleService。为整个应用程序(在 bootstrap 级别)或组件(providers 属性)定义提供程序。

bootstrap(AppComponent, [ HTTP_PROVIDERS, SampleService ]);

@Component({
  providers: [ HTTP_PROVIDERS, SampleService ]
})
export class SomeComponent {
  constructor(private action: SampleAction) {
  }

  executeAction() {
    this.action.doSomething();
  }
}

这是您应该用于 SampleAction class 的代码:

export default class SampleAction {
  constructor(private _projectService: SampleService) {
  }
}

您可以注意到,要能够注入服务,需要使用 @Injectable

@Injectable()
export class SampleService {
  constructor(public http: Http) {}
}

这个答案可以给你更多关于使用依赖注入的方式以及层次注入器在 Angular2 中如何工作的提示:

  • What's the best way to inject one service into another in angular 2 (Beta)?

不要使用 new SomeService() 创建服务实例。

相反,只需将 类 添加到 bootstrap(.., [Providers]) 的提供者或应该是共享服务实例的范围的根的组件。

还将所有依赖项(构造函数参数)添加到提供者列表中。

如果所有设置都正确,构造函数参数请求实例的任何地方,都会传入一个自动解析所有依赖项的实例。

只需配置 DI,让它为您完成工作。

在您的操作中,您可以在构造函数中注入 Http 并将其传递到服务实例中。像

export default class SampleAction {
    private _projectService;
    constructor(@Inject(Http) http: Http) {
        this._sampleService = new SampleService(http);
    }    
}