angular / in-memory-web-api

The code for this project has moved to the angular/angular repo. This repo is now archived.
MIT License
1.18k stars 231 forks source link

Can't access the provided InMemoryDbService directly #172

Closed j0wey closed 6 years ago

j0wey commented 6 years ago

I added some methods for initialization purposes of the mock data to my implementation of the InMemoryDbService and want to access it in a component.

As far as I understand, HttpClientInMemoryWebApiModule lists my implementation of the InMemoryDbService, that I hand over in the forRoot method, in its providers array as InMemoryDbService. So it should be possible to access the Service in other components in the constructor with constructor(private myInMemoryDataService: InMemoryDbService) {} and use it with this.myInMemoryDataService.myInitializationMethod();.

But this fails because of an error that my initialization method is not implemented. If I add my service to the providers array of my root module it works, but then it seems I have to instances of the service. One with my correctly initalized data and one without which is used by the Angular in-memory-web-api.

Is it possible what I want to achieve and if so, how? What do I have to import in my component to get the right instance of the InMemoryDbService?

LambdaCruiser commented 6 years ago

Inject the InMemoryDbService in the constructor and cast it to your specific implementation type. This is not pretty but should work.

private myInMemoryDbService : MyInMemoryDbService;

constructor(inMemoryDbService: InMemoryDbService) {
    this.myInMemoryDbService = <MyInMemoryDbService>inMemoryDbService;
}
wardbell commented 6 years ago

@LambdaCruiser Is exactly right. It is registered in DI under InMemoryDbService which knows nothing about your extensions. You cast it as suggested to gain TypeScript access to those.

This is how DI works everywhere in Angular. I don't think there is any action to take on this issue and therefore I am closing it.