用注入的服务扩展Angular Component方法 [英] Extend Angular Component method with injected services

查看:30
本文介绍了用注入的服务扩展Angular Component方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在提供装饰功能的外部模块中处理Angular组件的销毁事件.不幸的是,当它包含对注入服务的引用时,我无法覆盖 ngOnDestroy()方法...如何遍历它或以其他方式实现相同的效果?

I have to handle Angular component's destruction event in my external module providing decorating function. Unfortunately I am unable to override ngOnDestroy() method when it contains references to injected services... How can I go over it or achieve the same effect other way?

Plnkr: https://plnkr.co/edit/YtczREB91A3t6rJ1uKks (中的错误)不应抛出ngOnDestroy())

如果有人对此感兴趣,这里是工作版本,这要归功于@estus的 Symbol()命题:

If anyone would be interested in this, here is the working version thanks to @estus'es proposition with Symbol(): https://plnkr.co/edit/nnxLswhPUGZR3ycBWojg

推荐答案

ngOnDestroy 方法被列出的装饰器覆盖.实际的问题是错误的上下文应用于了

ngOnDestroy method is overridden with listed decorator. The actual problem with it is that wrong context is applied to originalFunction in

originalFunction.apply(target, arguments);

在使用方法/属性修饰符的情况下 target 参数是实例属性/方法的类原型:

In case of method/property decorators 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 是类构造器:

If ngOnDestroy method doesn't necessarily exist but the decorator should be applied any way, it can be class decorator instead, where target is class constructor:

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

这篇关于用注入的服务扩展Angular Component方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆