Angular2:观看除angular之外的外部变量 [英] Angular2: Watch an external variable outside of angular

查看:72
本文介绍了Angular2:观看除angular之外的外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够观察和更新angular2之外的变量.因此,假设我在一个外部javascript文件中拥有此文件:

I want to be able to watch and update when a variable outside of angular2 changes. So let's say I have this in an external javascript file:

var test = 1;

如何将此变量绑定到组件中的属性?

How can I bind this variable to a property in a component?

@Component({
   ...
})

export class MyComponent {
    watchy = window.test;
}

显然,根据此答案,这应该可以解决.
但事实并非如此.如果在控制台中更改变量,则该变量不会更新显示在模板中.我想念什么吗?

Apparently this should just work, according to this answer.
But it doesn't. If I change the variable in the console, the variable does not update displayed in a template. Am I missing something?

推荐答案

Angular仅在异步执行的函数完成时才运行更改检测.该函数需要在Angulars区域内运行,以便能够识别异步操作.

Angular only runs change detection when an async executed function completes. The function needs to be run inside Angulars zone for angular to recognize the async operation.

因为您的变量已从Angulars区域之外更改. Angular不会运行更改检测.

Because your variable is changed from outside Angulars zone. Angular doesn't run change detection.

您需要手动调用更改检测,以便Angular识别更改后的变量.另请参见手动触发Angular2更改检测

You need to invoke change detection manually for Angular to recognize the changed variable. See also Triggering Angular2 change detection manually

例如,如果您可以调度事件而不仅仅是设置变量,那么您可以侦听该事件.

If you for example can dispatch an event instead of just setting a variable, you can listen to the event.

window.dispatchEvent(new CustomEvent('test', {detail: 'newValue'}));

@Component({
   ...
})
export class MyComponent {
    @HostListener('window:test', ['$event'])
    testListener(event) {
      this.watchy = event.detail;
    }
}

调用的事件处理程序会自动调用Angulars更改检测,因此无需执行其他操作.

Invoked event handlers automatically invoke Angulars change detection, therefore there is nothing more to do.

这篇关于Angular2:观看除angular之外的外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆