Angular DI and inheritance: injecting extensions of a base service

后端 未结 1 1005
一个人的身影
一个人的身影 2020-12-12 04:52

I have a base service and two inhering services:

@Injectable({ providedIn: \'root\' })
export class BaseService {
  foo(src?: string){
    return `speaking f         


        
相关标签:
1条回答
  • 2020-12-12 05:32

    SomeService and AnotherService inherit the decorator metadata from BaseService, so angular injects an instance of BaseService in their place.

    This is dangerous, as calling any instance member from either SomeService or AnotherService which isnt inherited from BaseService will trigger a run-time error.

    The simplest way to archive the behavior you are looking for, would be to inherit from a common abstract base class, with no decorator:

    export abstract class AbstractBaseService {
      foo(src?: string) {
        return `speaking from ${src || 'AbstractBaseService'}`;
      }
    }
    
    @Injectable({ providedIn: 'root' })
    export class BaseService extends AbstractBaseService {
      foo() {
        return super.foo('BaseService');
      }
    }
    
    @Injectable({ providedIn: 'root'})
    export class SomeService extends AbstractBaseService {
      foo() {
        return super.foo('SomeService');
      }
    }
    
    @Injectable({ providedIn: 'root' })
    export class AnotherService extends AbstractBaseService {
      foo() {
        return super.foo('AnotherService');
      }
    }
    

    I modified your plnkr to test this approach.

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