skip to Main Content

Im working on typescript-angular project, where i have created a base class as follow:

export abstract class MyClass {
    constructor(private toastService?: ToastService) {}
    ...
}

I have extended MyClass in another class as bellow:

export class AcademyDraftListService extends AssessmentsDataService{
    constructor() {
        super()
    }
}

Now if i don’t pass toastService from parent then, in child it’s always null. Can i implement any other approach to use fallback service if parent class does not pass the service?

I knew for variables we can do something like this in parent:

constructor(private myVar?: ToastService='some value')

But how to achieve same thing for Services in angular?

2

Answers


  1. Angular will not inject any services to your parent class. You have to add it to the constructor of your child class too and pass it to the constructor of your parent class.

    export abstract class MyParentClass {
        constructor(private myService?: MyService) {}
        ...
    }
    
    export class MyClass extends MyParentClass {
        constructor(myService?: MyService) {
          super(myService);
        }
        ...
    }
    

    Also there is nothing like a fallback service. While you can create a new instance of the service as default value by yourself, you won’t be using Angulars dependency injection, which might cause problems or be complicated if the service has also dependecies.

    export abstract class MyParentClass {
        constructor(private myService: MyService = new MyService()) {}
        ...
    }
    

    Alternatively, you can try using Angulars Injector to fetch the service, although you’ll also need to inject it into your child class or create a new instance.

    Best practices would be to pass the service from the child class to the parent class in the constructor.

    Login or Signup to reply.
  2. To answer to you directly, in Angular 16 you have the inject function :

    export class MyBaseClass {
      private toaster = inject(ToasterService);
    }
    

    Not in the constructor = No need to inject it through the super call.

    Now, to give my two cents on the issue : in Angular, you should avoid extending your classes. Angular works with decorators, that are not extended, and it can lead to pretty strange errors. The correct approach to use in Angular is composition (implementing interfaces like OnInit), or dependency injection.

    So instead of creating a base class, create an injectable service and use it like so :

    export class MyBaseClass {
      doSomething() {}
    }
    
    export class MySubClass {
      private base = inject(MyBaseClass);
      doSomething = this.base.doSomething.bind(this.base);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search