【问题标题】:How to prevent passing parameter in constructor of typescript class when class uses other services in angular?当类以角度使用其他服务时,如何防止在打字稿类的构造函数中传递参数?
【发布时间】:2020-09-09 19:06:28
【问题描述】:

我想为我的项目的可扩展结构使用 Angular 类和服务机制。

我创建了一个组件,名为:汽车 我创建了一个类,名为:wheel 我创建了一项服务,名为:rotate

现在按照我的流程。

car 组件如下所示:

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 类是这样的:

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

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

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

我已经尝试过这段代码,它在 car 组件的 regarding that 1 argument required but you send 0 argument... 中的轮类初始化时给了我错误

在上面的两个代码中。 Wheel 类构造函数需要一个参数来在car 组件中初始化该类。但我不想将任何参数传递给 wheel 类的构造函数。

有没有办法在不将提供者参数传递给构造函数的情况下进行这种初始化类对象的流程?

没有将它传递给构造函数的主要原因是各种类使用了许多服务,并且它的所有导入都在基本主组件中是某种奇怪的东西。

如果有人对此有解决方案,请帮助我。

【问题讨论】:

  • 这在 Angular 中可能不是一个非常现实的场景......而且,这只是大多数语言中类继承的工作方式(实际上与 Angular 无关)。因此,在您的 Wheel 课程中,您假设 DI 工作我猜?但是,您可以简单地不在那里 DI 服务并自己实例化它。那么这将工作正常..

标签: angular class inheritance service


【解决方案1】:

我本来希望将 rotateService 注入汽车组件,并将 wheelRotate 传递给 Wheel。

如果您不想使用构造函数,为什么不在轮子上使用带有 WheelRotate 参数的旋转方法?

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

【讨论】:

  • 感谢您快速回复我,但实际上,这只是一个例子。我有复杂的类和服务项目结构...我可以将旋转功能放入我的类中,我的问题将解决但我还有另一个问题....因为我的一个代码,我使用来自@ionic/angular 的平台来获取设备的宽度,所以我怎样才能将该平台参数...移动到类中。我不知道...
【解决方案2】:

在打字稿中,您可以通过在名称后添加问号来指定可选参数,如下所示

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

    constructor(private rotateService?: Rotate){

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

请注意,您必须检查 rotateService 是否存在,因为当您不指定可选参数的值时,它的值是 undefined

【讨论】:

  • 嘿伙计,非常感谢您的回复,我会在我的项目中尝试这个解决方案。
猜你喜欢
  • 2017-04-01
  • 2019-07-05
  • 2015-04-12
  • 2017-01-29
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 2018-06-08
相关资源
最近更新 更多