I am instantiating MyService in app.module.ts, and providing it throughout my code.
However, I want MyService to use httpClient, and I am unable to angular-idiomatically instantiate httpClient to pass as a parameter to MyService. I'm not sure what the right way to access httpClient in MyService is.
I've looked at instantiating httpClient directly and then passing it as a parameter to my service. However it seems this creates a circular dependency. I have also tried messing with Injectors but this is specifically advised against by the Angular team apparently. I strongly feel I am missing something simple.
app.module.ts
imports: [
...
httpClientModule
...
],
function MainServiceFactory() {
return new MyService();
}
...
providers: [{
provide: MyService,
useFactory: MainServiceFactory
}],
...
MyService.ts
...
constructor(private http : HttpClient) {
...
}
Without instantiation and passing as parameter of httpClient: I get an "error in app.module.ts, expected 1 argument", naturally! With instantiation I break angular recommendations.
Edit: I had neglected to specify that I did import the httpClientModule
As everyone say, you have to import HttpClientModule
Looking to your code, I think you are trying to deal with angular's dependency injection
:
I did an example in the stackblitz:
https://stackblitz.com/edit/angular-yqvlv7?file=src%2Fapp%2Fapp.module.ts
Where I define an abstract class to behave like an interface, and then my.service
implements this interface.
Inside the app.module, I provide the 'interface' using my-service
class. After all this, you can inject the 'interface' in the component (in this link, hello.component.ts)
The HttpClient
is injected only in my-service
and there is no problem at all.
I hope it helps you to understand it better.
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