【发布时间】:2017-08-11 01:06:58
【问题描述】:
我正在努力寻找一种将服务注入 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) 我会做 new Product(product, productService) 。这似乎乏味且容易出错。我宁愿从类中导入引用,而不是弄乱构造函数。
我已经尝试过 ReflectiveInjector:
let injector = ReflectiveInjector.resolveAndCreate([ProductService]);
this.productService = injector.get(ProductService);
但是,这会产生一个错误 No provider for Http! (ProductService -> Http) at NoProviderError.BaseError [as constructor](而且我很确定这会创建一个新的 productService,因为我只是想引用在应用程序级别实例化的单例)。
如果有人知道可行的解决方案,我会很高兴听到。现在我将通过构造函数传递引用。
谢谢
【问题讨论】:
标签: class angular service dependency-injection