0

Module A

declarations: [myComponent]
providers: [myServiceA]

Module B

declarations: [myComponent]
providers: [myServiceB]

myComponent Shared by Module A and B

class myComponent {
  constructor(?) {}
}

myServiceA and myServiceB share the same API. The idea is that myServiceA stores the data locally (lets say localstorage) and myServiceB stores the data on the remote server (lets say Firebase).

How do I inject the correct myService, based on the module the component is loaded from?

1
  • This might work if you make the modules lazy loaded. Otherwise I think it's difficult. Commented Nov 16, 2016 at 11:56

1 Answer 1

2

I figured out how to do this:

  1. Create abstract class for myServiceA and myServiceB which exposes the same API used by both services.

    class abstract ParentService{
     someFunc: (arg: string) => any;
    }
    
    class myServiceA implements ParentService{
     // myServiceA implementation for someFunc
    }
    
    class myServiceB implement ParentService{
     // myServiceB implementation for someFunc
    }
    
  2. Inject parent class in component.

     class myComponent {
        constructor(service: ParentService) {}
    }
    
  3. Add different providers in Module A and B

Module A

declarations: [myComponent]
providers: [ { provide: ParentService, useClass: myServiceA } ]

Module B

declarations: [myComponent]
providers: [ { provide: ParentService, useClass: myServiceB } ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.