Angular 2 组件中的继承



我正在使用ANgular 2在当前项目中实现动态表单系统,到目前为止进展顺利,但我发现了以下问题:

我有两个表示表单控件的组件,例如:

@Component({
selector: 'app-text-area',
templateUrl: './text-area.component.html',
styleUrls: ['./text-area.component.css']
})
export class TextAreaComponent implements OnInit {
label: string;
formGroup: FormGroup;
formControlName: string;
constructor(private injector: Injector) { }
ngOnInit() {
this.label = this.injector.get('label');
this.formGroup = this.injector.get('formGroup');
this.formControlName = this.injector.get('formControlName');
}
}

和:

@Component({
selector: 'app-input-text',
templateUrl: './input-text.component.html',
styleUrls: ['./input-text.component.css']
})
export class InputTextComponent  implements OnInit{
label: string;
formGroup: FormGroup;
formControlName: string;
constructor(private injector: Injector) { }
ngOnInit() {
this.label = this.injector.get('label');
this.formGroup = this.injector.get('formGroup');
this.formControlName = this.injector.get('formControlName');
}
}

如您所见,除了显示不同 html 元素的 templateUrl 之外,两者是相同的。

因此,我想重构代码并创建一个抽象组件来提供公共属性和逻辑,然后使子类继承基类(就像我在使用 Java 时所做的那样(。所以我创建了这个类:

export class AbstractFormControl implements OnInit {
label: string;
formGroup: FormGroup;
formControlName: string;
constructor(private injector: Injector) { }
ngOnInit() {
this.label = this.injector.get('label');
this.formGroup = this.injector.get('formGroup');
this.formControlName = this.injector.get('formControlName');
}
}

我让子类像这样扩展基类:

@Component({
selector: 'app-input-text',
templateUrl: './input-text.component.html',
styleUrls: ['./input-text.component.css']
})
export class InputTextComponent  extends AbstractFormControl{
} 

但是现在我收到以下错误:

Uncaught Error: Can't resolve all parameters for InputTextComponent: (?).

有人可以解释一下这样做的正确方法是什么,或者我做错了什么?

角度依赖注入系统应该知道哪个类型已经传递给构造函数。当你以这种方式继承组件时,打字稿不会保留有关参数private injector的信息。您有两种选择:

1( 重复初始化

@Component({
...
})
export class InputTextComponent  extends AbstractFormControl{
constructor(injector: Injector) { super(injector);}
}

但是在您的情况下,您的基类和继承类中有相同数量的参数,并且此解决方案似乎是多余的,因为我们可以在派生类中省略构造函数。

如果我们只想使用父类的依赖项,我们可以在派生类中省略构造函数。 因此,假设我们有父类,例如:

abstract class Parent {
constructor(private a: string, private b: number) {}
}

我们可以扩展这个类

class Foo extends Parent {
constructor(a: string, b: number) {
super(a, b);
}
}

class Foo extends Parent {
}

因为第二个选项将生成类似

function Foo() {
return _super !== null && _super.apply(this, arguments) || this;
}

普伦克示例

2( 将@Injectable用于基类。

@Injectable()
export class AbstractFormControl {

这样打字稿会将上面的代码翻译成

AbstractFormControl = __decorate([
core_1.Injectable(),
__metadata("design:paramtypes", [core_1.Injector])
], AbstractFormControl);

普伦克示例

角度反射器可以轻松读取此信息

3( 对每个参数使用@Inject()

export class AbstractFormControl implements OnInit {
constructor(@Inject(Injector) private injector: Injector) { }

最新更新