ngOnDestroy
方法被列出的裝飾器覆蓋。與它的實際問題是錯誤的上下文中
originalFunction.apply(target, arguments);
應用於originalFunction
在方法/屬性的裝飾target
argument is class prototype for instance properties/methods的情況下:
export const ON_DESTROY_SYMBOL = Symbol();
export function Decorator() {
return (target: any, propertyName: string) => {
target[ON_DESTROY_SYMBOL] = target.ngOnDestroy;
target.ngOnDestroy = function() {
this[ON_DESTROY_SYMBOL]();
console.log('Component destroy event successfully handled!');
}
}
}
如果ngOnDestroy
方法不一定存在,但裝飾應該是應用任何方式,它可以類裝飾器代替,其中target
是類構造函數:
export function Decorator() {
return (target: any, propertyName: string) => {
target.prototype[ON_DESTROY_SYMBOL] = target.prototype.ngOnDestroy ||() => {};
target.prototype.ngOnDestroy = function() {
this[ON_DESTROY_SYMBOL]();
console.log('Component destroy event successfully handled!');
}
}
}
...
Decorator()
Component(...)
class ...
我想喲你應該首先使用你的服務實現ngOnit,然後用ngOndestroy來銷燬它。 –
'ngOnInit'對此沒有任何關係。正如你可以在演示路由器中看到的,正確地在構造函數內注入。 –