Sanjeev
Sanjeev

Reputation: 855

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?

Upvotes: 4

Views: 590

Answers (3)

Vidhya Sudhakar
Vidhya Sudhakar

Reputation: 36

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);
    }    
}

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202266

In fact you don't need to instantiate the service by your own. Just inject the service into a component or another service. What is important is to have the provider configured for this execution flow. In your case, Http (and more generally HTTP_PROVIDERS) and SampleSampleService. Providers are defined for the whole application (at the bootstrap level) or for component (providers attribute).

bootstrap(AppComponent, [ HTTP_PROVIDERS, SampleService ]);

or

@Component({
  providers: [ HTTP_PROVIDERS, SampleService ]
})
export class SomeComponent {
  constructor(private action: SampleAction) {
  }

  executeAction() {
    this.action.doSomething();
  }
}

Here is the code you should use for your SampleAction class:

export default class SampleAction {
  constructor(private _projectService: SampleService) {
  }
}

You can notice that to be able to inject into a service, the @Injectable need to be used.

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

This answer could give you more hints about the way to use dependency injection and how hierarchical injectors work in Angular2:

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657731

Don't create a service instance using new SomeService().

Instead just add the classes to the providers of bootstrap(.., [Providers]) or the component that should be the root of the scope where a service instance should be shared.

Also add all dependencies (constructor arguments) to the providers list.

If all is set up correctly, everywhere where an instance is requested by a constructor argument, an instance with all dependencies automatically resolved is passed in.

Just configure DI and let it do the work for you.

Upvotes: 0

Related Questions