gpt4 book ai didi

angular - 在父组件中使用单个 ngOnDestroy

转载 作者:行者123 更新时间:2023-12-03 23:28:17 29 4
gpt4 key购买 nike

在我们的应用程序中,我们有一些组件继承自 BaseComponent。 .

基础组件实现 OnDestroy接口(interface)并发出 Subject 来通知 child 取消订阅最终打开的流。

这是一种可接受的方法吗?或者更确切地说,每个组件都应该有自己的ngOnDestroy执行?从此article我读到生命周期 Hook 是 不是 遗传。

基础组件

export abstract class ComponentBase implements OnDestroy {
protected destroy$ = new Subject<boolean>();

ngOnDestroy() {
this.destroy$.next(true);
}
}

子组件
export class ChildComponent extends ComponentBase implements OnInit {

ngOnInit() {
this.service
.getById(userId)
.pipe(takeUntil(this.destroy$)) // this is emitted by the parent
.subscribe(user => { ...}
}
}

最佳答案

Is this an acceptable approach or rather every single component should have its own ngOnDestroy implementation?



可接受只是一个意见问题,但出于以下原因,我强烈反对这种方法。
@Component({...})
export class MyComponent extends BaseComponent implements OnDestroy {
public ngOnDestroy() {
// do work
}
}

export class BaseComponent implements OnDestroy {
public ngOnDestroy() {
// never executed
}
}

上面的示例没有发出 TypeScript 警告, super 方法永远不会执行,因此我很想将其称为反模式。

此外,将来您会很想添加额外的生命周期 Hook ,例如 OnInit到基类。为此,您必须搜索所有后代以确保他们调用 super.ngOnInit() .

虽然看起来工作量更大,但使用封装更安全。
export class BaseComponent implements OnDestroy {
public ngOnDestroy() {
// do work
}
}

@Component({...})
export class MyComponent implements OnDestroy {
private readonly _base: BaseComponent = new BaseComponent();
public ngOnDestroy() {
this._base.ngOnDestroy();
}
}

网上有很多关于封装与继承之间优缺点的文章。这实际上是计算机科学中的一个冗长的讨论,并且某些编程语言因为这些问题而专门不支持继承。我想我想说这是一个广泛的话题,是你个人选择的问题,但这也是你问这个问题的部分原因。

https://www.developer.com/design/article.php/3525076/Encapsulation-vs-Inheritance.htm

关于angular - 在父组件中使用单个 ngOnDestroy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56395879/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com