我正在尝试连接使用Http服务的基本Angular2应用程序. (我见过的大多数教程都是通过让一个组件使用Http服务来实现的,除非瘦控制器的基本原理发生了变化,否则这似乎是错误的 – 但这是一个不同的问题.)
我想创建一个使用Angular的Http服务的服务.但我无法弄清楚如何注入除此之外的Http服务:
boot.ts:
- import {bootstrap} from 'angular2/platform/browser';
- import {AppComponent} from './app.component';
- import {HTTP_PROVIDERS } from 'angular2/http';
- bootstrap(AppComponent,[HTTP_PROVIDERS]);
myService.ts:
- import {Injectable} from 'angular2/core';
- import {Http} from 'angular2/http';
- @Injectable()
- export class aService{
- constructor(http:Http){
- }
- /** do some stuff *//
- }
这是有效的,但要求服务的用户知道服务的依赖性并且需要将它们注入引导过程似乎是非常错误的.似乎应该有一种方法可以将提供者数组直接交给服务,就像组件一样,但我找不到它.我只是错过了一些东西吗?
更新
这样,如果父注入器为OtherService提供了一个实现,则使用此实现,否则使用OtherServiceImpl(默认).
- @Injectable()
- class SomeService {
- OtherService _other;
- SomeService(Injector injector) {
- _other = injector.getOptional(OtherService);
- if (_other == null) {
- _other = injector.resolveAndCreateChild([
- provide(OtherService,useClass: OtherServiceImpl)
- ]).get(OtherService);
- }
- _other.doSomething();
- }
- }
如果你提供另一个喜欢的
- bootstrap(AppElement,[
- provide(OtherService,useClass: OtherServiceImpl2)
- ]);
使用OtherServiceImpl2.
另见https://github.com/angular/angular/issues/5622
原版的
您可以将http服务设置为可选(使用@Optional()注释),如果没有提供,只需使用新的Http()在构造函数内创建一个实例.
这样,用户不需要知道服务依赖性,但是如果需要,可以传递替代实现(例如用于测试).
如果在服务中创建依赖项需要DI本身,则可以注入一个注入器并使用它来获取依赖项.
另请参见http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html中的可选依赖项
什么也可以工作(尚未尝试过)只是创建一个子注射器并指示它跳过自我
来自SkipSelfMetadata文档
- class Dependency {
- }
- @Injectable()
- class NeedsDependency {
- dependency;
- constructor(@SkipSelf() dependency:Dependency) {
- this.dependency = dependency;
- }
- }
- var parent = Injector.resolveAndCreate([Dependency]);
- var child = parent.resolveAndCreateChild([NeedsDependency]);
- expect(child.get(NeedsDependency).dependency instanceof Depedency).toBe(true);
- var inj = Injector.resolveAndCreate([Dependency,NeedsDependency]);
- expect(() => inj.get(NeedsDependency)).toThrowError();
如果父母不能提供所要求的类型,我还不知道这是否仍然从“自我”解决.