【问题标题】:Angular >= 2.x modify component method using decoratorsAngular >= 2.x 使用装饰器修改组件方法
【发布时间】:2017-07-12 22:10:44
【问题描述】:

其目标是一种非侵入性技术,用于跟踪用户对所需组件行为的操作...点击和其他内容。

我喜欢装饰器如何修改行为,但我不确定这是不可能的,还是我做错了。

如果这行得通,它基本上就像原始事件处理程序的包装器一样。只需通过处理程序上的装饰,我就可以轻松地跟踪和取消跟踪事件。但我的目标是不要用这个用户跟踪层“弄脏”处理程序逻辑。同样方便的是,使用某些组件上下文调用装饰器,并且不需要显式编码上下文。该上下文信息可能对日志记录有用。

app.component.ts

import { Component } from '@angular/core';
import { CaptureUserEvent } from 'app/user-action-tracker';

@Component({
    template: `
<h1>
  {{title}}
</h1>
<a href="#" (click)="setTitleText($event)">Test</a>
`,
    selector: 'app-root',
    styleUrls: ['./app.component.css'],
})
export class AppComponent {
    title = 'app works!';

    getElementText(elt:HTMLElement) {
        return elt.innerText;
    }

    @CaptureUserEvent
    setTitleText(ev:Event):void {
        console.log('called setTitleText');
        let newText = this.getElementText(<HTMLElement>ev.target);
        this.title = newText;
    }
}

user-action-tracker.ts

function CaptureUserEvent(cls, methodName, propertyDefinition):any {
    var oldMethod = cls[methodName];

    // this ultimately doesn't work... the AppComponent class retains the original function when it runs
    cls[methodName] = function (ev:Event) {
        console.log('called wrapper');

        // log event...

        oldMethod(ev);
    };
}

export {
    CaptureUserEvent
}

有没有正确的方法可以做到这一点,或者有类似的方法可以实现相同的目标?

【问题讨论】:

    标签: angular angular-decorator


    【解决方案1】:

    修改描述符的值就可以了:

    function CaptureUserEvent(cls, methodName, descriptor): void {
      let oldMethod = descriptor.value;
    
      descriptor.value = (ev: Event) => {
        console.log('called wrapper');
    
        oldMethod.call(cls, ev);
      };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      • 2016-10-30
      • 2018-02-14
      • 2017-03-15
      • 2020-01-11
      相关资源
      最近更新 更多