Angular 6 Services and Class Inheritance

前端 未结 1 566
终归单人心
终归单人心 2020-12-31 07:40

Angular 6 now has injectable providers which is the new recommended way of injecting services, and it works really well except I\'m having a problem when using a service whi

相关标签:
1条回答
  • 2020-12-31 08:04

    Update:

    There is already a pull request for that https://github.com/angular/angular/pull/25033

    Original version

    The problem: seems new angular treeshakable services don't respect inheritance:

    First angular defines(1) ngInjectableDef property on AppService function. Then you inherit ChilAppService from AppService so that child class contains all properties from parent class. And finally when angular tries to define(2) ngInjectableDef property on ChildAppService it can't because it already exists(3) thanks to javascript prototypical inheritance.

    In order to fix it you can either

    1) workaround it through defining undefined ngInjectableDef property on child service so that it won't read already filled from parent class property and angular will be able to define ngInjectableDef on child class:

    @Injectable({
      providedIn: 'root'
    })
    export class ChildAppService extends AppService {
      static ngInjectableDef = undefined;
      constructor() {
        super();
        this.name = 'CHILD SERVICE';
      }
    }

    Forked stackblitz

    2) or report issue in github

    3) or use composition instead of inheritance as was suggested in comments.

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