gpt4 book ai didi

websocket - Angular2 Dart ngFor在使用WebSockets时不更新 View

转载 作者:行者123 更新时间:2023-12-03 02:57:11 25 4
gpt4 key购买 nike

我一直在与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( String data )
我要在模板中使用的成员:List data;OnMessage方法内部的赋值:data = res[ "data" ];
有什么奇怪的发现吗?
也许类成员和方法参数具有相同的名称?
也许这意味着该参数使成员蒙上阴影?
也许这意味着对该名称的分配实际上是参数而不是成员的分配?

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

更改两条线,一切正常

  • void OnMessage( String data ) => void OnMessage( String response_data )
  • Map res = JSON.decode( data ); => Map res = JSON.decode( response_data );
  • 关于websocket - Angular2 Dart ngFor在使用WebSockets时不更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37461682/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com