2017-07-07 59 views
1

我必須在提供裝飾功能的外部模塊中處理角度組件的銷燬事件。不幸的是,當它包含對注入服務的引用時,我無法覆蓋ngOnDestroy()方法......我怎樣才能克服它或通過其他方式實現相同的效果?使用注入服務擴展角度組件方法

Plnkr:https://plnkr.co/edit/YtczREB91A3t6rJ1uKks(錯誤ngOnDestroy()不應隨意)

如果有人有興趣在此,這裏是工作版本感謝@ estus'es命題與Symbol()https://plnkr.co/edit/nnxLswhPUGZR3ycBWojg

+0

我想喲你應該首先使用你的服務實現ngOnit,然後用ngOndestroy來銷燬它。 –

+0

'ngOnInit'對此沒有任何關係。正如你可以在演示路由器中看到的,正確地在構造函數內注入。 –

回答

1

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 ... 
+0

是的,它通過重寫來擴展......問題是:我應該如何調用'originalFunction'來避免注入服務的問題?那麼,它是一個存儲變量在localStorage等(ngx-store)的屬性裝飾器 –

+0

用try ... catch包裝它..在這一點上,這看起來更像XY問題。目前還不清楚爲什麼在原始ngOnDestroy中容忍這些錯誤(他們顯然不應該)。 – estus

+0

Try-catch沒有意義,因爲我不想改變默認行爲和方法覆蓋這種方式只是停止工作... –