class - 将服务注入(inject)类(不是组件)Angular2

标签 class angular service dependency-injection

我正在努力寻找一种方法将服务注入(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/

相关文章:

angular - 将本地开发的模块打包/导入到项目中

android - 如何让 Android 应用程序无限期运行?

java - Android 音乐播放器无法从 onCreate 自动启动

Java Scanner 类读取字符串

C++ 为什么在传递类指针时调用析构函数?

java - 将数组从类中分离出来

jquery - 使用 jQuery append 到 div 并应用基于类的 css 样式

java - Angular 火 : How to perform some operations on data before updating template

angular - 使用 *ngFor 和 [(ngModel)] 通过 Map 更改对象数组

ubuntu - 在 Ubuntu 上通过 Ansible 将 Java Jar 作为服务运行