Home > other >  How to use factory Angular with interface?
How to use factory Angular with interface?

Time:09-13

Here is an interface:

interface Service {
  make(): void;
  get(): any;
}

And two services that implement this contract:

class Service1 implements Service {
   constructor(private rootService: RootService) {}
   make() {}
   get() {}
}


class Service2 implements Service {
   constructor(private rootService: RootService) {}
   make() {}
   get() {}
}

I need to use the concrete implementation of service in component A and component B with the same name but with the different implementation:

class Component A {
  constructor(private service: Service) {}
}

class Component B {
  constructor(private service: Service) {}
}

How to do that considering the service has dependency: private rootService: RootService?

CodePudding user response:

In theory, you could just provide different implementations for the Service interface at the component level (assuming that Service1 and Service2 are stateless).

To circumvent the fact that the interface cannot be used as an injection token, you can create a new injection token for this purpose:

export const MY_SERVICE = new InjectionToken<Service>('MY_SERVICE');
@Component({
  // ...,
  providers: [{
    provide: MY_SERVICE,
    useClass: Service1
  }]
})
class Component A {
  constructor(@Inject(MY_SERVICE) private service: Service) {}
}
// ...
@Component({
  // ...,
  providers: [{
    provide: MY_SERVICE,
    useClass: Service2
  }]
})
class Component B {
  constructor(@Inject(MY_SERVICE) private service: Service) {}
}
  • Related