不允许使用Angular2多个构造函数实现TS2392 [英] Angular2 multiple constructor implementations are not allowed TS2392
问题描述
如何在一个组件中使用多个构造函数?目前,我收到错误消息:
How can I get around using multiple constructors within a component? Currently I am getting the error:
不允许使用多个构造函数实现".
'Multiple constructor implementations are not allowed'.
questions: any[];
constructor( service: QuestionSignupStepOneService ) {
this.questions = service.getQuestions();
}
constructor( service: QuestionSignupStepOneAService ) {
this.questions = service.getQuestions();
}
无论如何,有没有简化我想要做的事情?该代码可以正确编译,但只能通过第一个服务运行,而忽略第二个服务.
Is there anyway to simplify what I am trying to do? The code compiles properly but will only run through the first service, ignoring the second.
推荐答案
使多个具有相同参数的构造函数没有意义,除非它们具有不同的类型,在Typescript中,您可以执行以下操作:
Making multiple constructors with the same parameters doesn't make sense unless they have different types, in Typescript you can do the following:
class Foo {
questions: any[];
constructor(service: QuestionSignupStepOneService, param2?: Param2Type) {
this.questions = service.getQuestions();
if(param2){
console.log(param2);
}
}
}
这等于两个构造函数,第一个是 new Foo(service)
,第二个是 new Foo(service,param2)
.
This is equal to two constructors, the first one is new Foo(service)
and the second one is new Foo(service, param2)
.
使用?
声明该参数是可选的.
Use ?
to state that the parameter is optional.
如果您希望两个构造函数具有相同的参数,但对于不同的类型,则可以使用以下方法:
If you want two constructors with the same parameter but for different types you can use this:
class Foo {
questions: any[];
constructor(service: QuestionSignupStepOneService | QuestionSignupStepOneAService) {
if(service instanceof QuestionSignupStepOneService){
this.questions = service.getQuestions();
}
else {
this.questions = service.getDifferentQuestions();
}
}
}
这篇关于不允许使用Angular2多个构造函数实现TS2392的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!