Mayur Kukadiya
Mayur Kukadiya

Reputation: 2747

How to prevent passing parameter in constructor of typescript class when class uses other services in angular?

I want to use angular class and service mechanism for my project's scalable structure.

I have created one component, named : car I have created one class, named : wheel I have created one service, named : rotate

Now according to my flow.

car component is look like this :

import { wheel } from './Class/wheel';

  @Component({
    selector: 'app-car',
    templateUrl: './car.page.html',
    styleUrls: ['./car.page.scss'],
  })

  export class car implements OnInit {

    car:any = [];
    wheelSection: Wheel;

    constructor(){
    }

    ngOnInit() {
      this.WheelSection =  new Wheel();   // I don't want to pass any parameter here..
     this.car.push(WheelSection);
    }

}

Wheel class is look like this :

import { Rotate } from '../Service/Rotate.service';

export class Wheel {
    
   wheelRing:any;
   WheelRotate:any;

    constructor(private rotateService: Rotate){
      this.WheelRotate = rotateService.rotate();
    }
}

I have tried this code and it is giving me error at the wheel class's initialization in car component's regarding that 1 argument required but you send 0 argument...

Here in above two code. Wheel class constructor needs one parameter for initialize that class in car component. but I don't want to pass any parameter into that wheel class's constructor.

Is there any way to do this kind of flow for initialize class object without passing provider parameter into constructor ?

The main reason is not passing that into constructor is that there are many services used by various classes and all it's import are in base main component is some kind of weird stuff.

Please help me if any one have a solution about this.

Upvotes: 0

Views: 1161

Answers (2)

ntoniocp
ntoniocp

Reputation: 32

In typescript you can specify optional parameters by adding a question mark after the name, like this

export class Wheel {
    
   wheelRing:any;
   WheelRotate:any;

    constructor(private rotateService?: Rotate){

        if (rotateService) {
          this.WheelRotate = rotateService.rotate();
        }
    }
}

Note that you will have to check if the rotateService exist, because when you don't specify the value of an optional parameter it has the value of undefined

Upvotes: 1

erik karlstrom
erik karlstrom

Reputation: 33

I would have expected the rotateService to be injected into the car component, and the wheelRotate to be passed to the Wheel.

If you don't want to use a constructor why not have a rotate method on wheel that takes a WheelRotate argument?

wheel = new Wheel();
wheel.initRotation(rotateService.rotate());

Upvotes: 1

Related Questions