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?
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) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With