我一直在尋找如何創建一個好的 Component 父級來改進我的代碼的 DRY。從 Component 繼承 Component 需要重復 ,constructor(<services>){}這與 DRY 目標背道而馳。我遇到了來自 Angular 的警告訊息,該訊息建議從指令繼承???所以我試了一下,它似乎作業。
您是否知道我將使用這種方法產生的任何風險或問題?
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];
}
uj5u.com熱心網友回復:
從 Angular 14 開始,您的用例有一個方便的功能 - 全域inject。您現在可以將依賴項從建構式中移開。所以不需要重復注射
class Parent {
service1 = inject(ServiceOne);
}
class Child extends Parent {
service2 = inject(ServiceTwo);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/515374.html
下一篇:角度驗證反應形式的多個選擇
