2016-05-26 27 views
1

我一直有一個angular2組件的問題。當我使用websockets時,視圖不會更新。我已經嘗試過使用http請求,它工作正常,但我需要保持視圖中的數據更新。Angular2 dart ngFor使用WebSockets時不更新視圖

我可以使用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; 
    } 
    } 
} 

我周圍的一派,看到了一些問題,像這樣的地方強迫變化decection與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> 

爲註釋中提到。我可以看到在開發者控制檯中打印的數據。它的格式正確,包含正確字段的地圖列表,但該頁面保持空白。

回答

2

原來我只是真的很蠢。

讓我們一起看看幾件事吧?

地處理輸入數據的方法簽名: 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);