Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add providers to a Service class in Angular 2?

I have a component that uses a service. The component looks something like this:

@Component({
    moduleId: module.id,
    selector: 'test',
    providers: [HTTP_PROVIDERS, TestService]
})
export class TestComponent implements OnInit {

    constructor(private _testService:TestService) {
    }

As you can see, I added the HTTP_PROVIDERS provider in my component. This worked since the DI is now aware of the http classes. However, it was my TestService that was really using the Http class, not my TestComponent.

@Injectable()
export class TestService {

    constructor(private _http:Http) {
    }

I felt that since it is the service using the Http class, it should be the one including the providers in itself. The TestComponent wouldn't know what providers TestService would need.

Since the service class doesn't have that component decorator, I'm not sure how I can actually add providers to it. How can I add providers to a Service class?

like image 740
Carven Avatar asked Oct 18 '22 06:10

Carven


1 Answers

What you can do is,

Inject HTTP_PROVIDERS into bootstrap function ,

import {HTTP_PROVIDERS} from '@angular/http';
bootstrap(AppComponent,[HTTP_PROVIDERS]);

and in your service,

import {Http} from '@angular/http';

@Injectable()
export class TestService {
    constructor(private _http:Http) {}
}
like image 191
Nikhil Shah Avatar answered Oct 31 '22 15:10

Nikhil Shah