【问题标题】:Angular2 - pass variable with EventEmitter by timeout function to parent componentAngular2 - 通过超时函数将带有EventEmitter的变量传递给父组件
【发布时间】:2017-06-08 01:11:30
【问题描述】:

我对子组件中的事件发射器有疑问。

我想将带有 EventEmitter 的变量传递给父组件,但具有使用超时功能。现在它看起来像这样:

孩子:

export class AlertSuccess implements OnChanges {

    @Input() success: SuccessCRM;
    @Output() emitCollapse:EventEmitter<any> = new EventEmitter();

    private info_ico: string = require('../../public/images/iconInfoTip.png');
    public state: boolean = false;

    constructor() {}

    collapseAlert () {
        let alert = document.getElementById('success');
        setTimeout(function() {
            console.log("BEFORE EMITTED STATE!!!!!: ", this.state );
            console.log(this.emitCollapse);
            this.emitCollapse.emit(this.state); 
        }, 500);
    }

    ngOnChanges(changes: SimpleChanges):void {
        console.log("CHANGES: ", this.success);
        this.collapseAlert();
    }
}

在父级中一切正常,我有通过模板传递的方法。

发射器在没有超时功能的情况下工作。请帮我实现超时!

问候 博斯珀!

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    使用Arrow function 指向正确的this。

    setTimeout(() => {
        console.log("BEFORE EMITTED STATE!!!!!: ", this.state );
        console.log(this.emitCollapse);
        this.emitCollapse.emit(this.state); 
    }, 500);
    

    【讨论】:

    • 作为对@Uland 的改进和评论,请记住在 ngOnDestroy 中清理超时。
    • @camaron 我认为清除超时并不重要,它会调用collapseAlert 函数,setTimeout 只会被调用一次,然后它就不会被调用。如果它会setInterval,那么 OP 必须在ngOnDestroy 生命周期事件中清除它..
    猜你喜欢
    • 2020-07-18
    • 2019-04-28
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 2020-07-28
    相关资源
    最近更新 更多