TL;博士
我们正在构建一个带有角2的应用程序,并希望注册一个“全局”的ngOnInit和ngOnDestroy函数。使用“全局”,我的意思是为每个组件执行函数,而不需要为每个组件显式地实现函数。这个是可能的吗?
详细
我们的一些组件(但不是所有组件)一旦加载(例如ngOnInit),就需要在全局服务中注册一些东西,并在卸载(例如ngOnDestroy)之后重新注销它。以下是我能想到的两种方法:
ngOnInit和ngOnDestroy中)。这两种方法都不太令人满意:
这就是为什么我想出了以下的想法:
为什么不将上面提到的抽象类替换为可以由所有所需组件实现的接口。然后,我将注册一个全局函数,该函数在所有组件的每个ngOnInit和ngOnDestroy上执行(如果可能的话--例如在模块、路由等中)。在函数中,我将检查组件是否实现了接口,如果实现了,则调用适当的函数来获得要注册的特定类型的内容。
我的问题
发布于 2016-09-10 03:41:59
强制整个应用程序的行为将不是一个好主意,这也会影响第三方组件以及初学者。
样板代码可以移动到具体的基类中。有用于JS/TS多重继承的解决方案,例如@mixin,也请参阅TypeScript指南。
由于基类方法是固定的,所以类mixin可以表示为简化的修饰器:
class CustomLifecycle implements OnInit, OnDestroy {
constructor(
public originalNgOnInit: Function,
public originalNgOnDestroy: Function
) {}
ngOnInit() {
...
if (typeof this.originalNgOnInit === 'function') {
this.originalNgOnInit();
}
}
ngOnDestroy() {
...
if (typeof this.originalNgOnDestroy === 'function') {
this.originalNgOnDestroy ();
}
}
}
function Lifecycled() {
return function (target: Function) {
const customLifecycle = new CustomLifecycle(
target.prototype.ngOnInit,
target.prototype.ngOnDestroy
);
target.prototype.ngOnInit = customLifecycle.ngOnInit;
target.prototype.ngOnDestroy = customLifecycle.ngOnDestroy;
}
}而且它可以像
@Component({ ... })
@Lifecycled()
class SomeComponent { .... }实现仅限于ngOnInit等原型方法,箭头成员需要对构造函数进行修补。
https://stackoverflow.com/questions/39420241
复制相似问题