1
votes

I have an existing code implementing singleton pattern by having private constructor and returning object instance returning the object -

export class SingletonFactory {
  private static factoryInstance = new SingletonFactory();

  private constructor() {
  }

  public static getInstance() {
    return SingletonFactory.factoryInstance;
  }
}

I need to inject a dependency into this factory. And I changed my code to the following -

@Inject('MyService')
export class SingletonFactory {
  private static factoryInstance = new SingletonFactory();

  private constructor(private myService : MyService) {
  }

  public static getInstance() {
    return SingletonFactory.factoryInstance;
  }
}

Please suggest, how I can inject the dependency at object creation in the constructor?

1
You have XY problem. Why exactly do you use SingletonFactory? Angular DI is supposed to manage singleton instances for you.Estus Flask
I inherited the code which had this factory. I am just trying to add a dependency; if I understand correctly, you are suggesting to convert this into an angular factory and let framwork take care of maintaining the singleton instance?SoftEngi
I suggest to use it as service service. It is already a singleton there. And it accepts classes. If you have problems with this approach, I'd suggest to update the question with relevant details. This isn't a typical AngularJS code. Does it use ng-metadata?Estus Flask
This is on AngularJS 1.5; the way injection is being done is again my code specificSoftEngi

1 Answers

0
votes

Inject into your component.

import { Router } from  '@angular/router';
    import { FormBuilder, FormGroup, Validators} from '@angular/forms';
    import { Location } from '@angular/common';
    constructor(public location: Location,public fb:FormBuilder,public global_service:GlobalService,public router: Router) { 

      }