Search code examples
javascriptangularangular2-services

How to pass an object to service constructor in NgModule of angular 2/4 app


So here is a service say MyService

MyService has a constructor in its implementation

@Injectable() 
export class MyService {
    constructor(myObject: MyClass) {}
}

Now myObject is of type MyClass which I need to pass while injecting the service

One way by which I can use MyService is

_myService = new MyService(new Myclass())

and then access methods in MyService

this._myService.someMethod();

But with this approach I have to do this in every component where I use MyService

I want to pass the value to MyService constructor in NgModule in providers array

So that in any component I need MyService I can just use by

export class MyComponent {
    constructor( _myService: MyService) {}
    this._myService.someMethod();
}

Solution

  • So I figured out how to do it

    It can be done by using useFactory in the following manner

    {
      provide: MyService, 
      useFactory: MyServiceFactory  
    }
    
    export function MyServiceFactory() {
      return new MyService(new MyClass());
    }
    

    This will pass the MyClass object which is required by MyService constructor and the service can be injected henceforth into any component.

    export class MyComponent {
      constructor( _myService: MyService) {}
    }