Angular 2 + SignalR - 从外部脚本访问 Angular 内部

Angular 2 + SignalR - Accessing Angular internals from external script

我将 SignalR 与 Angular2 应用程序一起使用,我们希望 SignalR 客户端方法使用从服务器接收到的数据调用 Angular 应用程序,然后 Angular 重做数据绑定。例如,在 Angular 应用程序中,我为我们的商店公开了一个全局变量,其中包含一个集合。

例如 (打字稿)

....
export class Store{
  Customers : Customer[];
  constructor(){
    window["GlobalStore"] = this;
  }

  setCustomers (customers : Customer[]){
    this.Customers = customers;
  }
}
....

在我的客户端 SignalR javascript 我有一个函数:

$.connection.MyHub.client.receive = function(data){
  //Call into the Angular app and set data, which is then rendered in views
  //via data-binding
  //data contains a json array of customers
  window.GlobalStore.setCustomers(data);
}

这似乎有效并在存储中设置数据,但是,当数据重置时 Angular 似乎没有检测到更改,因此 UI 没有刷新。

这不是数据输入的问题,因为即使将简单的 string/integer 等传递给商店,在我调试时也会正确设置商店 属性,但是,Angular框架似乎不会触发更改检测并刷新视图。

关于如何: A) 手动触发 angular 数据绑定以便刷新视图? B) 使用不同的方式从外部调用 Angular 2 应用程序中的方法?

谢谢

要手动 运行 更改检测:

  1. 使用ApplicationRef::tick()方法。
  2. 使用 NgZone::run() 方法包装应在 angular 区域内执行的代码。

您可以通过使用依赖注入或使用 platform().application(bindings).bootstrap(Component):

引导您的应用程序来获取它们
import { platform } from 'angular2/angular2';

const app = platform().application([] /* - bindings */); // you can use `app.tick()` 
const zone = app.zone; // you can use `zone.run`

app.bootstrap(Component);