首页 > 解决方案 > Angular:在没有@Injectable 装饰器的情况下注入类

问题描述

我有一些来自图书馆的课程,例如:

class Foo {
   // ...
}
class Bar {
   constructor(private foo: Foo) { }
   // ...
}

这些类没有@Injectable装饰器,因为库不是 Angular 特定的。但是,我想在我的应用程序中将它们用作服务。

到目前为止,我的解决方案是创建派生类,例如:

@Injectable()
class InjectableFoo extend Foo {
  constructor() { super(); }
}
@Injectable()
class InjectableBar extends Bar {
  constructor(foo: InjectableFoo) {
    super(foo);
  }
}

我对这个解决方案不是很兴奋,因为它需要额外的样板代码,没有增加任何实际价值,并且在组件中使用这些服务的人必须知道使用“可注入”版本而不是(更简单的)基础类。在一个完美的世界里,我希望能够告诉 AngularFoo并且Bar应该是可注入的。

这可能吗?

标签: angular

解决方案


您可以在NgModule使用工厂提供者和价值提供者时提供它们。

https://angular.io/api/core/FactoryProvider

https://angular.io/api/core/ValueProvider

class Foo {
   // ...
}
class Bar {
   constructor(private foo: Foo) { }
   // ...
}

@NgModule({
   providers: [
      {provide: Foo, useValue: new Foo()},
      {provide: Bar, useFactory: (foo) => new Bar(foo), deps: [Foo]}
   ]
});

在上面的示例中,您可以使用useValue: new Foo(),但这里的关键是deps: [Foo]允许您注入foo工厂函数,Bar因为它是一个依赖项。

稍后在组件中,您可以执行以下操作。

@Component({...})
export class MyComponent {
    constructor(foo: Foo, bar: Bar) { }
}

推荐阅读