代码之家  ›  专栏  ›  技术社区  ›  Kris

Angular-如何访问注释类方法

  •  0
  • Kris  · 技术社区  · 8 年前

    我有以下角度注释声明:

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

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

    1 回复  |  直到 8 年前
        1
  •  0
  •   Kris    8 年前

    通过添加这一行,编译器不会再抱怨了,它可以工作。

    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();
            }
        }
    }