2015-11-20 43 views
1

我使用SignalR与Angular2应用程序,我们希望SignalR客户端方法使用从服务器接收的数据调用Angular应用程序,然后使用Angular重做数据绑定。例如,在Angular应用程序中,我为我们的商店公开了一个全局变量,它有一个集合。Angular 2 + SignalR - 从外部脚本访问角内部

E.g. (打字稿)

.... 
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); 
} 

这似乎不过工作,并设置在存储中的数据,当数据被重置角度做似乎没有检测到更改,因此UI未刷新。

这不是数据类型的问题,因为即使将一个简单的字符串/整数等传递到存储区,我也会在调试时正确设置存储属性,但是,Angular框架似乎没有触发更改检测,刷新看法。

任何想法如何: A)手动触发角度数据绑定,使其刷新视图? B)使用不同的方法从外部调用Angular 2应用程序内的方法?

感谢

回答

1

要手动运行变化检测:

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

可以使用依赖注入或通过使用自举的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); 
+0

谢谢@alexpods。 .tick()方法是否仅在alpha 46中添加?我试图找到45但没有运气......如果我移动到46,我可以有一个组件如下: export class MyClass { 构造函数(私人applicationRef:ApplicationRef){ } makeItTick(){ this.applicationRef.tick(); } } –

+1

在alpha46之前有'LifeCycle :: tick()'方法具有相同的目的。看到[这个SO答案](http://stackoverflow.com/questions/33174146/angular-2-0-equivalent-to-scope-apply/33175487#33175487)。 'LifeCycle'在alpha 46中被删除。 – alexpods

+0

是的,你可以注入'applicationRef'然后使用它的'tick'方法。我认为,你编写的代码将起作用。 – alexpods