【问题标题】:Angular - How to access annotation class methodAngular - 如何访问注释类方法
【发布时间】:2018-06-16 12:07:38
【问题描述】:

我在 Angular 中有以下注释声明:

class ModalContainer {
    public destroy: Function;
    public closeModal() {
        this.destroy();
    }
}

export function Modal() {
    return function (target: any) {
        Object.assign(target.prototype, ModalContainer.prototype);
    };
}

我想在组件内部使用注解:

@Component({
    selector: 'my-component',
    templateUrl: 'my-component.template.html',
    styleUrls: ['my-component.style.scss']
})
@Modal()
export class MyComponent implements OnInit {
    private EVENT_SAVE = 'EVENT_SAVE';
    private EVENT_CANCEL = 'EVENT_CANCEL';
    private buttonClick(event: any, eventType: string){
        if (eventType === this.EVENT_CANCEL){
            this.closeModal();
        } else if(eventType === this.EVENT_SAVE){
            this.closeModal();
        }
    }
}

问题是,TypeScript 无法编译,因为此方法在编译时是未知的。但是,当我在模板中使用相同的方法调用时,它就可以工作了。这意味着,原型已分配。

编译器显示此错误消息:

ERROR in [at-loader] ./src/main/webapp/ui/src/my-component.component.ts:128:18
    TS2339: Property 'closeModal' does not exist on type 'MyComponent'.

有谁知道,我怎么解决这个问题?

【问题讨论】:

    标签: javascript angular typescript annotations angular5


    【解决方案1】:

    通过添加此行,编译器将不再抱怨并且可以正常工作。

    private closeModal: Function;
    

    这个类看起来像这样:

    @Component({
        selector: 'my-component',
        templateUrl: 'my-component.template.html',
        styleUrls: ['my-component.style.scss']
    })
    @Modal()
    export class MyComponent implements OnInit {
        private EVENT_SAVE = 'EVENT_SAVE';
        private EVENT_CANCEL = 'EVENT_CANCEL';
        private closeModal: Function;
        private buttonClick(event: any, eventType: string){
            if (eventType === this.EVENT_CANCEL){
                this.closeModal();
            } else if(eventType === this.EVENT_SAVE){
                this.closeModal();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 2013-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多