Cor*_*ada 4 service dependency-injection class angular
我正在努力寻找一种将服务注入 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;
}
Run Code Online (Sandbox Code Playgroud)
我想出的唯一解决方案是在我创建新产品时将服务引用传递给构造函数......即:而不是new Product(product)我会做new Product(product, productService)。这看起来很乏味而且容易出错。我宁愿从类中导入引用,而不是弄乱构造函数。
我试过 ReflectiveInjector:
let injector = ReflectiveInjector.resolveAndCreate([ProductService]);
this.productService = injector.get(ProductService);
Run Code Online (Sandbox Code Playgroud)
但是,这会产生一个错误No provider for Http! (ProductService -> Http) at NoProviderError.BaseError [as constructor](而且我很确定这会创建一个新的 productService,当我只想引用在应用程序级别实例化的单例时)。
如果有人知道一个可行的解决方案,我会很高兴听到它。现在我将通过构造函数传递引用。
谢谢
我在一个类似的问题上苦苦挣扎,我最终做的是使服务成为单例以及可注入的 Angular。
通过这种方式,您可以通过 DI 注入 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;
}
}Run Code Online (Sandbox Code Playgroud)
无法将服务注入到普通类中。Angular DI 仅注入组件、指令、服务和管道 - 仅注入 DI 创建实例的类,因为这是注入发生的时间。
要从自定义注入器获取Http,您需要添加到它的提供程序,如Angular 2 中手动注入 Http中所示
或者你传递一个提供它们的父注入器
// constructor of a class instantiated by Angulars DI
constructor(parentInjector:Injector){
let injector = ReflectiveInjector.resolveAndCreate([ProductService]);
this.productService = injector.get(ProductService, parentInjector);
}
Run Code Online (Sandbox Code Playgroud)
另请参阅https://angular.io/docs/ts/latest/api/core/index/ReflectiveInjector-class.html