0

I have an angular app animals, which displays a picture of an animal depending on the current route location. For example, /dog will display dog picture and /cat will display the cat picture on the page.

To accomplish it, I have created 3 feature modules - AnimalBoxModule, CatModule and DogModule. AnimalBoxModule has a component AnimalBoxComponent and a service AnimalService. AnimalBoxComponent uses AnimalService.getPicture() to get the image of the animal. DogModule and CatModule has DogService and CatService which can be used to provide custom implementation of AnimalService to display picture of cat and dog respectively.

I am rendering <animal-box></animal-box> in the AppComponent. To display the right picture of animal, I have to provide service implementation (CatService or DogService) depending on the current route location. How is it possible in Angular?

Thanks in Advance

Edit

I dont want to make any changes in AnimalBoxComponent which is using the service, because I am presenting it as a reusable component. IMO, it would not be a good idea to change it whenever we want to extend this app to have more animal services.

Moazzam Khan
  • 3,130
  • 2
  • 20
  • 35
  • hmmm... usually it's better to have separate components if they use different services. but I can see how you could want this. Have you tried using the `ActivatedRouteSnapshot`? – FussinHussin Oct 09 '17 at 13:58
  • @FussinHussin No, did not know about it. Going to try that. Thanks – Moazzam Khan Oct 09 '17 at 15:57
  • you can check to see if a string matches the activated route, like dog or cat, and inject the service based on that. the hardest part will be figuring out how to conditionally inject a service. – FussinHussin Oct 09 '17 at 17:21
  • Thanks @FussinHussin, Conditionally injecting a service, where I am stuck. Any pointers or hints would be highly appreciated. – Moazzam Khan Oct 10 '17 at 07:27

1 Answers1

0

Alright, it looks like you can do this using the Angular Injector, there is a post here that answers your question.

import { Injector } from '@angular/core'  
...
constructor(private injector: Injector){ 

  if(true) {
    this.oneService = <OneService>this.injector.get(OneService);
  } else {
    this.twoService = <TwoService>this.injector.get(TwoService);
  }
}

I would read the post as it has more info on the why.

FussinHussin
  • 1,718
  • 4
  • 19
  • 39
  • Thanks for your answer, I am sorry for I haven`t explained my problem well. I have added the explanation in the problem statement, why I am not in favour of this solution. – Moazzam Khan Oct 11 '17 at 09:24
  • hmm, okay I understand that. I'm not sure of another way, you might consider starting a bounty – FussinHussin Oct 12 '17 at 14:24