我正在努力寻找一种方法将服务注入(inject)到 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)
我会做 新产品(产品,产品服务)
。这看起来很乏味而且容易出错。我宁愿从类中导入引用,也不要弄乱构造函数。
我试过 ReflectiveInjector:
let injector = ReflectiveInjector.resolveAndCreate([ProductService]);
this.productService = injector.get(ProductService);
但是,这会产生错误 No provider for Http! (ProductService -> Http) at NoProviderError.BaseError [as constructor]
(而且我很确定这会创建一个新的 productService,当我只是想引用我在应用程序级别实例化的单例时)。
如果有人知道可行的解决方案,我会很高兴听到。现在我将通过构造函数传递引用。
谢谢
最佳答案
我一直在努力解决类似的问题,而我最终所做的是使服务成为单例以及 Angular 可注入(inject)。
这样你就可以通过 DI 注入(inject) Angular 类并调用静态 getInstance()
方法来获取类的单例实例。
像这样:
import {Injectable} from "@angular/core";
@Injectable()
export class MyService {
static instance: MyService;
static getInstance() {
if (MyService.instance) {
return MyService.instance;
}
MyService.instance = new MyService();
return MyService.instance;
}
constructor() {
if (!MyService.instance) {
MyService.instance = this;
}
return MyService.instance;
}
}
关于class - 将服务注入(inject)类(不是组件)Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42892002/