websocket - Angular2 dart ngFor 使用 WebSocket 时不更新 View

标签 websocket angular dart dart-html

我在使用 angular2 组件时遇到了问题。当我使用 websockets 时, View 不会更新。我尝试过使用 http 请求,效果很好,但我需要保持 View 中的数据更新。

我可以使用 websockets 很好地连接到服务器,并且可以接收数据,但我的 View 没有更新。

@Component(
  selector: "pv-table",
  templateUrl: "./table.component.html"
)

class TableComponent
{
  WebSocket _connection;

  // NgZone _zone;
  // ApplicationRef _application_ref;

  List data;

  TableComponent(/* this._zone, this._application_ref */)
  {
    _connection = new WebSocket( "ws://${HOST}:${PORT}" );

    _connection.onOpen.first.then( ( _ ) {
      _connection.onMessage.listen( ( MessageEvent e ) => OnMessage( e.data ) );

      // A simple class that gives my application a standard
      // way to communicate.
      Packet request = new Packet()
        ..message = "table.get"
        ..data    = {};

      _connection.send( JSON.encode( request ) );

      _connection.onClose.first.then( ( _ ) { });
    });
  }

  void OnMessage( String data )
  {
    Map    res = JSON.decode( data );
    String cmd = res[ "message" ];

    Log.Info( cmd );

    switch( cmd )
    {
      case "table.send":
        // Setting the data here. This works
        data = res[ "data" ];

        // This prints the correct data in the developer console.
        Log.Info( data ); 

        // Neither of these help.
        // _zone.run( () => data = res[ "data" ] );
        // or
        // _application_ref.tick();

        break;

      default:
        Log.Warn( "Unknown command: $cmd" );
        break;
    }
  }
}

我用谷歌搜索了一下,发现了一些类似这样的问题,即使用 NgZone.run(...)ApplicationRef.tick() 强制进行更改检测,但是没有帮助。要么它们不适用于这种情况,要么我不知道如何使用它们。

我的模板如下所示:

<p *ngFor="let person of data">
  <span scope="row">{{ person[ "_id" ] }}</span>
  <span>{{ person[ "name" ] }}</span>
  <span>{{ person[ "job" ] }}</span>
  <span>{{ person[ "date_due" ] }}</span>
</p>

正如评论中提到的。我可以看到开发者控制台中打印的数据。它的格式正确,是具有正确字段的 map 列表,但页面仍为空白。

最佳答案

事实证明我真的非常非常愚蠢。

让我们来看看一些事情吧?

处理传入数据的方法的签名: void OnMessage( 字符串数据 )

我尝试在模板中使用的成员: 列出数据;

OnMessage 方法内部的赋值: data = res[ "data"];

注意到什么奇怪的事情了吗? 也许类成员和方法参数具有相同的名称? 也许这意味着参数正在隐藏成员? 也许这意味着对该名称的分配实际上是对参数而不是成员的分配?

最糟糕的是我已经坐在这里近两个小时试图找出问题所在。

更改两行,一切正常

  • void OnMessage(字符串数据) => void OnMessage(字符串response_data)
  • 映射 res = JSON.decode( data ); => 映射 res = JSON.decode( response_data );

关于websocket - Angular2 dart ngFor 使用 WebSocket 时不更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37461682/

相关文章:

json - Dart编程查询:读取GET的响应

django websockets 无法在 channel 上发送消息

azure - 如何使用安全 WebSockets (wss) 在 Azure 应用服务的 Docker 容器中设置 nginx?

java - 更新 JHipster 后不再提供 Angular 组件,仅提供 root index.html

typescript - 如何在 Angular 2/Typescript 中声明一个全局变量?

dictionary - Dart Map.remove哪里没有删除所有符合删除条件的键

node.js - 如何按名称或特定端口列出 Socket.io 房间

node.js - Websockets - 避免未知连接

spring - 尝试运行 npm run build 时出错

flutter - 如何等待一个已经在执行的方法?