Home > Software engineering >  How to pass arguments and inject services to angular class?
How to pass arguments and inject services to angular class?

Time:04-25

A question seems fairly simple, but I don't work with OOP at all. I have a parent class. I want it to have service injected into constructor and to pass every argument needed in parent class. I just want to have an abstract class from which I can create more complex classes.

Let's say parent class looks like this:

export class FormComponent {
  constructor(childArgs: someType, private readonly SthService){
    this.sth = childArgs.sth;
    // etc
  }
}

where childArgs are arguments that I want to pass down to parent component and private readonly SthService is an injectable service I want to use in the component

The child class looks like that

@Component({
  selector: '...',
  templateUrl: './....html',
  styleUrls: ['./....scss']
})
export class ChildComponent extends FormComponent {
constructor(){
  super({
    firstProp: X,
    secondProp: Y,
    thirdProp: Z,
  });
}

What am I doing wrong? Can I just pass the arguments and have service injected altogether? Because right now it says that there SthService is undefined.

CodePudding user response:

use @inject('variable name') to pass other objects. I am assuming your service class name is ServiceClass.

    export class FormComponent {
        constructor(@Inject('childArgs') childArgs: any, private readonly SthService: ServiceClass){
          this.sth = childArgs.sth;
          // etc
        }
    }

CodePudding user response:

You are not providing correct parameters of base class FormComponent in derived class ChildComponent. So your constructor of ChildComponent should look like this:

export class ChildComponent extends FormComponent {
    constructor(childArgs: someType, private readonly SthService){
      super(childArgs, SthService)
    }
}

It is necessary to pass necessary arguments of constructor of base class in derived class.

So this is a code example of sending parameters to base class:

class Human {
    constructor(
        public name: string,
        public age: number
    ){}
}


class Employee extends Human {
    constructor(
        public name: string,
        public age: number,
        public dateHired: Date
    ) {
        super(name, age)
    }
}
  • Related