如何配置angular2 Injectable

时间:2016-06-06 15:14:39

标签: angular

在AngularJS中,我可以使用

在应用程序级别配置服务
myApp.config(function(unicornLauncherProvider) {

});

参考: https://docs.angularjs.org/guide/providers

angular2等价物是什么?

2 个答案:

答案 0 :(得分:0)

Angular2支持基于构造函数的依赖注入。为了能够在引导应用程序时或在组件的providers属性内注入需要指定其关联提供程序的东西。

以下是一个示例:

bootstrap(AppComponent, [ UnicornLauncher ]);

@Component({
  (...)
  providers: [ UnicornLauncher ]
})

然后您可以在构造函数参数中指定类型:

constructor(private launcher:UnicornLauncher) {
}

请注意,您需要围绕相应类的装饰器,例如ComponentInjectable

修改

如果你想"配置"如果是提供商,您可以将provide功能与useFactory

一起使用
bootstrap(AppComponent, [
  provide(UnicornLauncher, { useFactory: () => {
    let ul = new UnicornLauncher();
    // configure
    return ul;
  })
]);

答案 1 :(得分:0)

我猜您正在研究如何使用提供商来配置您的服务注入方式,是吗?

如果是这样,让我们​​以Thierry发布的为例。

<强>提供商: [UnicornLauncher]只是告诉angular如何实例化服务的更简洁方法。 这就是有角度理解的:

[new Provider(UnicornLauncher, {useClass: UnicornLauncher})]

假设您想在注入UnicornLauncher时使用其他类:

[new Provider(UnicornLauncher, {useClass: UnicornLauncherCustom})]

有许多方法可以配置您自己的提供商。我建议你看一下角度文档。

https://angular.io/docs/ts/latest/guide/dependency-injection.html?The%20Provider%20class%20and%20provide%20function#!#providers

此致