角度组件继承_WITHOUT_,重复构造函数



我一直在寻找如何创建一个好的Component父级,以改进代码的DRY。从组件继承组件需要重复constructor(<services>){},这与DRY目标背道而驰。我偶然发现Angular的一条警告消息,建议从指令中继承???所以我试了一下,似乎有效。

你知道我用这种方法会带来什么风险或问题吗?

有角度的文档提示";摘要";指令,所以这里可能有一些故意的东西。在任何情况下,stackblitz上都有一个工作示例。下面是关键的父文件和子文件的整体。

import { Directive, OnDestroy } from '@angular/core';
import { Tag, TagSubject } from './tag.store';
@Directive()  // This was the unexpected success
export class BaseTagDirective implements OnDestroy {
subs: any = [];
tag: Tag;
constructor(  // This is the constructor I did NOT want to repeat
private tagstore: TagSubject
) {
this.tag = new Tag();
}
subTag(tagname: string) {
this.subs.push(
this.tagstore.subject(tagname).asObservable().subscribe((tag: any) => {
this.tag.name = tag.name;
this.tag.value = tag.value;
})
);
}
ngOnDestroy() {  // unrelated to the question, just a subscription tidy up.
for (let i = 0; i < this.subs.length; i++) {
this.subs[i].unsubscribe();
}
}
}

由此产生的孩子是。。。

import { Component, OnInit, Input } from '@angular/core';
import { BaseTagDirective } from './base.directive';
@Component({
selector: 'app-value',
templateUrl: './value.component.html'
})
export class ValueComponent extends BaseTagDirective implements OnInit {
@Input() tagname: any;
// look no constructor :D

ngOnInit() {
this.subTag(this.tagname);
}
}

父级引用的标记存储包括以下项。

update(tagname: string, value: number) {
this.tags[tagname].value = value;
this.subjects[tagname].next(this.tags[tagname]);
}
subject(tagname: string) {
this.subjects[tagname] = new BehaviorSubject<Tag>(this.tags[tagname]);
this.subjects[tagname].next(this.tags[tagname]);
return this.subjects[tagname];
}

Angular 14中有一个适用于您的用例的方便功能-全局inject。现在,您可以将依赖关系从构造函数中移除。因此无需重新注射

class Parent {
service1 = inject(ServiceOne);
}
class Child extends Parent {
service2 = inject(ServiceTwo);
}

最新更新