Angular2 dart ngFor 在使用 WebSockets 时不更新视图

Angular2 dart ngFor not updating view when using WebSockets

我一直在使用 angular2 组件时遇到问题。当我使用 websockets 时,视图不会更新。我已经尝试使用 http 请求并且它工作正常,但我需要更新视图中的数据。

我可以使用 websockets 连接到服务器,我可以接收数据,但我的视图没有更新。

@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>

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

原来我真的很蠢。

让我们来看看一些事情好吗?

处理传入数据的方法的签名: void OnMessage( String data )

我试图在模板中使用的成员: List data;

OnMessage方法里面的赋值: data = res[ "data" ];

注意到什么奇怪的事了吗? 也许 class 成员和方法参数同名? 也许这意味着参数正在影响成员? 也许这意味着对该名称的赋值实际上是对参数而不是成员的赋值?

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

改变两行,一切正常

  • void OnMessage( String data ) => void OnMessage( String response_data )
  • Map res = JSON.decode( data ); => Map res = JSON.decode( response_data );