Search code examples
angularreduxangular2-servicesinjectableprovider

How to inject a provider in Angular 2 service from action?


I am trying to remove the dependency of components on services in Angular with the help of Redux.

Basically, the flow is Component -> Action -> Service

In the service I want to use http module of @angular/core, which is suggested to be passed in the constructor:

export class SampleService {
    constructor(public http: Http) {}
}

And as I am calling service from action, it won't get the http provider as I do not have an instance of http provider in it.

export default class SampleAction {
    private _projectService;
    constructor() {
        this._sampleService = new SampleService();
    }
}

How can I inject the http provider into the service?


Solution

  • In your action you can inject the Http in constructor and pass it into the service instance. Something like

    export default class SampleAction {
        private _projectService;
        constructor(@Inject(Http) http: Http) {
            this._sampleService = new SampleService(http);
        }    
    }