How to override inject() dependency from abstract base class in Angular?

Discussão em 'Angular' iniciado por Raphaël Balet, Agosto 19, 2025.

  1. I have an abstract base class that used to accept a service via constructor injection:

    export abstract class BaseEditEventClass<T> extends BaseFormClass {
    constructor(protected _service: BaseEditEventService<T>) {
    super();
    }
    }


    In the subclasses, I could provide a more specific service like this:

    export class FooBarComponent extends BaseEditEventClass<FooBar> {
    constructor(protected override _service: FooBarService) {
    super(_service);
    }
    }


    Now that Angular recommends using the inject() function instead of constructor injection, I tried this in the base class:

    export abstract class BaseEditEventClass<T> extends BaseFormClass {
    protected readonly _service = inject(BaseEditEventService<T>);
    }


    But then I don’t see how the child class can override that with its own service, e.g. FooBarService.

    export class FooBarComponent extends BaseEditEventClass<FooBar> {
    // how do I inject FooBarService instead of BaseEditEventService<T> ?
    }


    What’s the correct way in Angular to let subclasses provide their own injected service when the base class uses inject()?

    Should the base class still declare the injection, or should I delegate that responsibility to the subclass?

    Is there an idiomatic Angular pattern for this with generics?

    Continue reading...

Compartilhe esta Página