Angular2 应用程序问题 - 必须执行该函数两次,以强制显示更改
Angular2 app issue - have to exec the function twice, to force the changes to appear
先看看我的笨蛋:
https://plnkr.co/edit/5x76J6i0rm5mmDRDO9QP
打开控制台并尝试单击并拖动轴。单击并移动轴时,将执行以下功能:
plot.on('plotly_relayout', () => {
console.log('relayouted');
this.someVar = false;
});
正如您将能够在控制台中看到的那样,它记录了 relayouted
消息,但是 someVar
仍然 未更改。
但是(这里出现了奇怪的、意想不到的部分)- 如果您再次单击图表(您甚至不必拖动它)someVar
最终会变成false。 (如我所愿)
我的问题是我想在函数执行后立即更改someVar
值。
这很奇怪,因为重新布局图表时会立即记录 console.log,但变量不会发生这种情况。
为什么我必须执行两次函数才能强制显示更改?
谢谢。
EDIT1:如果您尝试 console.log 那个变量:
plot.on('plotly_relayout', () => {
console.log('relayouted');
this.someVar = false;
console.log(this.someVar);
});
它会在第一次执行时记录 false
。所以这将是某种悖论,因为变量是假的,但在视图中显示为真!奇怪...
当您收听外部库事件时,您必须确保在事件内部您 运行 在您的 angular 上下文中。
试试这个:
从@angular/core
导入 NgZone
然后将 public zone: NgZone
添加到您的构造函数中,最后将您的代码替换为下一个。
let plot = document.getElementById('plotly');
plot.on('plotly_relayout', () => {
this.zone.run(() => {
console.log('relayouted');
this.someVar = !this.someVar;
});
});
这是您的 plunker,进行了这些更改:https://plnkr.co/edit/Zqvxpv5tyQ0AIIK7Iapw?p=preview
先看看我的笨蛋:
https://plnkr.co/edit/5x76J6i0rm5mmDRDO9QP
打开控制台并尝试单击并拖动轴。单击并移动轴时,将执行以下功能:
plot.on('plotly_relayout', () => {
console.log('relayouted');
this.someVar = false;
});
正如您将能够在控制台中看到的那样,它记录了 relayouted
消息,但是 someVar
仍然 未更改。
但是(这里出现了奇怪的、意想不到的部分)- 如果您再次单击图表(您甚至不必拖动它)someVar
最终会变成false。 (如我所愿)
我的问题是我想在函数执行后立即更改someVar
值。
这很奇怪,因为重新布局图表时会立即记录 console.log,但变量不会发生这种情况。
为什么我必须执行两次函数才能强制显示更改?
谢谢。
EDIT1:如果您尝试 console.log 那个变量:
plot.on('plotly_relayout', () => {
console.log('relayouted');
this.someVar = false;
console.log(this.someVar);
});
它会在第一次执行时记录 false
。所以这将是某种悖论,因为变量是假的,但在视图中显示为真!奇怪...
当您收听外部库事件时,您必须确保在事件内部您 运行 在您的 angular 上下文中。
试试这个:
从@angular/core
导入 NgZone然后将 public zone: NgZone
添加到您的构造函数中,最后将您的代码替换为下一个。
let plot = document.getElementById('plotly');
plot.on('plotly_relayout', () => {
this.zone.run(() => {
console.log('relayouted');
this.someVar = !this.someVar;
});
});
这是您的 plunker,进行了这些更改:https://plnkr.co/edit/Zqvxpv5tyQ0AIIK7Iapw?p=preview