【问题标题】:Angular 2 + SignalR - Accessing Angular internals from external scriptAngular 2 + SignalR - 从外部脚本访问 Angular 内部
【发布时间】:2016-02-22 09:11:26
【问题描述】:

我将 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 没有刷新。

这不是数据类型的问题,因为即使将简单的字符串/整数等传递给商店,我调试时也会正确设置商店属性,但是,Angular 框架似乎不会触发更改检测和刷新意见。

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

谢谢

【问题讨论】:

    标签: javascript angular signalr


    【解决方案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);
    

    【讨论】:

    • 谢谢@alexpods。 .tick() 方法是否仅在 alpha 46 中添加?我试图在 45 中找到但没有运气......如果我移动到 46,我是否可以拥有一个组件,如下所示:export class MyClass{ constructor(private applicationRef: ApplicationRef){ } makeItTick() { this.applicationRef.tick(); } }
    • 在 alpha 46 之前有 LifeCycle::tick() 具有相同目的的方法。见this SO answerLifeCycle 在 alpha 46 中被删除。
    • 是的,你可以注入applicationRef,然后使用它的tick方法。我认为,您编写的代码会起作用。
    • 请注意,您可以使用从angular2/core (Plunker) 导入的ChangeDetectorRef 对象的detectChanges() 方法对当前组件运行更改检测。 tick 方法会触发整个应用程序的更改检测。
    猜你喜欢
    • 2017-02-14
    • 2018-03-19
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 2018-02-17
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多