0

I have a service in Angular that inherits from an abstract class and implements an abstract method.

@Injectable({
  providedIn: 'root',
})
export class ClassB extends ClassA { 

constructor(
    private service : ExampleService) {
    super();
  }

  abstractMethod() {
   //this.service returns undefined here
  }

} 

export abstract class ClassA { 

  abstractMethod();
  
  otherMethod() { 
    this.abstractMethod();
  }
}

However, in the constructor of ClasseB I need to inject a service that will be used within the abstract method.

The abstract method is executed inside "otherMethod ()" in the Abstract class, as the abstractMethod () method has no implementation in the Parent class, it will call the implementation inside the child class, however, at that moment it returns undefined.

How do I get to use a service instance within the abstractMethod ()?

Basically, what I need is to be able to get a service instance inside "abstractMethod ()", it is currently returning undefined.

Geferson
  • 115
  • 5
  • I'm thinking it's a simple as marking `ClassA.abstractMethod` as `abstract`. https://stackoverflow.com/questions/13333489/declaring-abstract-method-in-typescript – Andrew Shepherd Mar 09 '21 at 00:48

1 Answers1

0

Why your code doesn't work

  • this.service is called in the abstract class ClassA.
  • ClassA doesn't know about a service property
  • Even if it did only ClassBService can access your service property since it has been scoped private.

The solution

  • add a service property to ClassA
  • give your service property a protected or public scope

The code below does something akin to what you want

    import { Injectable } from "@angular/core";
    import { HelloService } from "./hello.service";
    
    abstract class ClassA {
      protected service: HelloService;
      public hello() {}
    
      protected say_hello() {
        this.service.hello();
      }
    }
    
    @Injectable()
    export class ClassBService extends ClassA {
      constructor(protected service: HelloService) {
        super();
      }
    
      public hello() {
        this.say_hello();
      }
  }
Rob Monhemius
  • 4,822
  • 2
  • 17
  • 49