将服务注入到类(不是组件)Angular2中 [英] Inject service into class (not component) Angular2
问题描述
我正在努力寻找一种将服务注入angular2中的类对象的方法.
I am struggling to find a way to inject a service into an class object in angular2.
*注:这不是组件,而只是一个类. *
export class Product {
id: number;
name: string;
manufacturer: string;
constructor(product: any) {
this.id = product.id;
this.name = product.name;
this.manufacturer = product.manufacturer;
}
我想出的唯一解决方案是,每当我创建新产品时,就将服务引用传递给构造函数...即:我会使用new Product(product, productService)
而不是new Product(product)
.这似乎很乏味且容易出错.我宁愿从类中导入引用,也不要弄乱构造函数.
The only solution I have come up with is to pass the service reference to the constructor whenever I create a new product... ie: instead of new Product(product)
I would do new Product(product, productService)
. This seems tedious and error prone. I would rather import the reference from the class and not messy up the constructor.
我已经尝试过ReflectiveInjector:
I have tried the ReflectiveInjector:
let injector = ReflectiveInjector.resolveAndCreate([ProductService]);
this.productService = injector.get(ProductService);
但是,这会产生错误No provider for Http! (ProductService -> Http) at NoProviderError.BaseError [as constructor]
(此外,我很确定当我只是想引用在应用程序级别实例化的单例时,也会创建一个新的productService.)
However, this creates an error No provider for Http! (ProductService -> Http) at NoProviderError.BaseError [as constructor]
(Also I'm pretty sure this creates a new productService when I simple want to reference my singleton that is instantiated at the app level).
如果有人知道一个可行的解决方案,我将很高兴听到它.现在,我将通过构造函数传递引用.
If anyone knows of a working solution I would be glad to hear it. For now i will pass the reference through the constructor.
谢谢
推荐答案
无法将服务注入普通类. Angular DI仅注入到组件,指令,服务和管道中,仅注入DI创建实例的类,因为这是注入发生的时间.
There is no way to inject a service into a plain class. Angular DI only injects into components, directives, services, and pipes - only classes where DI creates the instance, because this is when injection happens.
To get Http
from a custom injector, you need to add to it's providers like shown in Inject Http manually in angular 2
或者您通过提供它们的父注入器
or you pass a parent injector that provides them
// constructor of a class instantiated by Angulars DI
constructor(parentInjector:Injector){
let injector = ReflectiveInjector.resolveAndCreate([ProductService]);
this.productService = injector.get(ProductService, parentInjector);
}
另请参见 https://angular.io/docs/ts/latest/api/core/index/ReflectiveInjector-class.html
这篇关于将服务注入到类(不是组件)Angular2中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!