【问题标题】:When does angular2 @output resolve?angular2 @output 什么时候解决?
【发布时间】:2018-01-08 23:43:37
【问题描述】:

考虑一下plunker

HTML

<chart [options]="options" 
       (load)="saveGraphInstance($event.context)"></chart>
<div (click)="switchGraph()">switch</div>
<div (click)="showLoadingForce()">show loading</div>

打字稿

class AppComponent {
    constructor() { 
        this.options = {
            title : { text : 'simple chart' },
            series: [{
                data: [29.9, 71.5, 106.4, 129],
            }],
            lang:{
                loading: 'your text here',
            },
        };
    }
    options: Object;
    graph: any;

    switchGraph() {
      this.options = {
            title : { text : 'different chart' },
            series: [{
                data: [129.9, 171.5, 106.4, 129],
            }],
            lang:{
                loading: 'your text here',
            },
        };
        this.graph.showLoading() // This doesn't work
        setTimeout(function() {
            this.graph.showLoading() // This also doesn't work
        }, 4000);
    }

    showLoadingForce() {
      this.graph.showLoading() // User clicked work
    }

    saveGraphInstance(graph) {
      this.graph = graph;
      //this.graph.showLoading() // after loading work
    }
}

我们从上面的代码中看到,在选项改变的同一个函数中,show loading 即使我设置超时时间超过 4 秒也不起作用

但如果它在load 触发器或用户启动之后完成,那么它总是有效。

这很有趣,所以我的问题如下

  1. 如果我点击switch div 并立即点击show loading div,加载文本将显示,然后setimeout 将执行(因为4 秒延迟),但只有setimeout 会遇到错误ERROR TypeError: Cannot read property 'showLoading' of undefined。这怎么可能?如果showLoadingForce 成功,则意味着saveGraphInstance 一定发生了

  2. (load) 何时执行和解析?在githubsource code找不到相关信息

【问题讨论】:

    标签: javascript angular typescript highcharts angular5


    【解决方案1】:

    关于第一季度,

    ERROR TypeError: Cannot read property 'showLoading' of undefined

    这是在setTimeout() 中访问this 的问题。 setTimeout 方法内部this 默认为window 对象。要解决此问题,请保存对 this 的引用,然后在 setTimeout 方法中访问它。

    参考the "this" problem.

    关于Q2,加载定义为ChartComponent中的输出ChartEvent绑定。这将调用 EventEmitter 的新实例。

    在setTimeout后使用以下代码隐藏加载图片:更新plunker

     saveGraphInstance(graph) {
          this.graph = graph;
          this.graph.showLoading();
          var that = this;
          setTimeout(function(graph) {
                that.graph.hideLoading();
            }, 4000);
        }
    

    JS API Reference

    【讨论】:

    • 嗯,我已经知道如果我把它放在 saveGraphInstance 中,我可以隐藏或显示,我的问题是为什么会发生这种情况以及 @output 何时解决
    • 你的例子中哪里有@output?
    • 在问题编号2 中,我链接了一个github 源,它是load 的源,在我的示例plunker 中链接到saveGraphInstance,但是我想知道何时执行顺序load 在 angular4 生命周期的上下文中执行,以更好地理解为什么会出现第 1 个问题。
    • @jal,您必须将 this 的引用传递给 setTimeout 方法,然后您就不会收到错误消息。 developer.mozilla.org/en-US/docs/Web/API/…
    • 你是对的,这确实是一个this 问题,并且根据mdn 看来load 是一个原生事件
    猜你喜欢
    • 2011-06-15
    • 2018-04-13
    • 2016-06-07
    • 2020-09-03
    • 1970-01-01
    • 2011-10-08
    • 2012-01-31
    • 1970-01-01
    相关资源
    最近更新 更多