我在使用 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/