Angular 2 Injectable Interface?

后端 未结 1 1416
情深已故
情深已故 2020-12-11 19:35

Today I stumbled upon something that I didn\'t think would cause me trouble.

In Java and Spring, I can declare two beans that both implement a given interface, while

相关标签:
1条回答
  • 2020-12-11 20:17

    In order for a provider to be injected, it should be registered as a provider. There's no IConfigurationService provider. And it cannot be a provider, because interfaces don't exist in compiled JS code.

    The common practice for interfaces that are supposed to be used as provider tokens is to be abstract classes:

    abstract class ConfigurationService { ... }
    
    @Injectable()
    class WebAppConfigurationService extends ConfigurationService { ... }
    
    ...
    providers: [{ provide: ConfigurationService, useClass: WebAppConfigurationService }]
    ...
    

    This recipe is commonly used by Angular 2 itself, e.g. abstract NgLocalization class and concrete NgLocaleLocalization implementation.

    0 讨论(0)
提交回复
热议问题