简体   繁体   English

Angular类似的Java服务依赖注入

[英]Angular like dependency injection of services in Javascript

I am writing a Javascript npm package. 我正在写一个Javascript npm包。 In my code I have a single class which I want to act like an angular service. 在我的代码中,我有一个单一的类,希望像一个角度服务一样工作。 Only one instance of that class should be created and needs to be shared wherever wanted in the project. 仅应创建该类的一个实例,并且需要在项目中的任何地方共享该实例。

//this class object would be shared across project and only one object can be created. also, its implementation could change in future
export class SharedClass {
    constructor(somethingImp) {
    }
    //more methods
}

export class ProjectClass1ThatNeedsSharedClassObj {
    //it should get the required object
}

export class ProjectClass2ThatNeedsSharedClassObj {
    //it should get the required object
}

How can I write a simple DI to achieve this functionality? 如何编写简单的DI来实现此功能?

If you want enforce a single object through all methods of DI, you can use a static variable. 如果要通过DI的所有方法强制执行单个对象,则可以使用静态变量。 This is the pattern I normally use 这是我通常使用的模式

export class SearchProvider {
  private static _default: SearchProvider

  constructor() {
  }

  static get Default() {
    return this._default || (this._default = new SearchProvider())
  }
}

export class Consumer() {
  private SearchProvider _provider = SearchProvider.Default;
}

1)Create that class as a service with @Injectable decorator 2)Import that class into class where you want to use it 3)create a instance of service class into that class 4)now you can access methods of service class using instance created in constructor using this keyword & . 1)使用@Injectable装饰器将该类创建为服务2)将该类导入要使用的类3)在该类中创建服务类的实例4)现在您可以使用在中创建的实例访问服务类的方法使用此关键字&的构造函数。 operator 5)You have to write service class once & use it many times as you want 操作员5)您必须编写一次服务类,并根据需要多次使用它

Happy coding 快乐编码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM