typescript类装饰器扩展方法

时间:2016-11-18 11:39:23

标签: angularjs typescript override aop decorator

我用打字稿搜索了很多关于装饰者的解释,但我没有找到完整的文件,我可以按照我的目的申请。

我找到了两个可能的解决方案:AOP和Decorator,但我知道aop“还没有准备好”。

这个想法是 - 我有一些安全库来实现,我需要在当前页面更改时调用一些方法“enterAction”和“leaveAction”。

我有用于页面更改(加载/离开)的角度/离子生命周期事件。 我想在一个地方“覆盖”它们,因为我不想修改每个页面组件。 (当我添加一个新的时,我将忘记实现它。)

所以我的想法是在每个页面类上添加一个装饰器。在这个装饰器中,当调用事件(加载/离开)时,添加对我的安全库的调用(输入/ leaveAction)。

实际上我可以在课堂上创建装饰器。但我不知道如何覆盖方法调用。

目前我定义了我的类装饰者谎言:

@security
@Component({
    selector: 'my-app',
    template: '<h1>Hello Angular!</h1>'
})
export class AppComponent implements OnInit {
    private toto= "demo";
    constructor() {
        console.log("construct!");
    }
    ngOnInit() {
        console.log('onInit');
        this.method1();
    }
    method1() {
        console.log('method 1 : '+ this.toto);
    }
}


function security<TFunction extends Function>(target: TFunction): TFunction     {
    var method1 = target.prototype.method1;
    Object.defineProperty(target.prototype, 'method1', {
        value: function() {
            console.log('enterAction here');
            // How to call real method1() here ?
            // Call of method1() will fail since it don't know AppCompnent.toto here
            return '';
        }
    });
    return target;
}

此致

修改

最后,我发现了另一种不使用装饰器解决问题的方法。

1 个答案:

答案 0 :(得分:2)

你非常接近,你只需要使用apply

function security<TFunction extends Function>(target: TFunction): TFunction     {
    var method1 = target.prototype.method1;
    Object.defineProperty(target.prototype, 'method1', {
        value: function() {
            console.log('enterAction here');
            return method1.apply(this, arguments);
        }
    });
    return target;
}
相关问题