2016-04-07 55 views
0

我通過套接字連接從後端獲取更新。我想用AngularJS自動更新Frontend,同時使用數據對象作爲我從後端得到的數據。如何在獲取套接字更新時更新AngularJS模板?

我有什麼?

模板:

Status: {{unit.getStatus()}} 

控制器1:

function ($scope, unitFactory) { 
    // register to unit factory to get the updates and do 
    // $scope.unit = data.getUnit(); 
} 

控制器2:

function ($scope, unitFactory) { 
    // register to unit factory to get the updates and do 
    // $scope.unit = data.getUnit(); 
    // $scope.foo = data.getFoo(); 
} 

服務:

function(requestFactory) { 
    var unit = {}, 
     foo = {}; 

    Sockets.socket('unit', function (response) { 
     unit = new Unit(response['data']); 
     foo = new Foo(response['foo']); 

     // This is the data object which has to be send to the controllers 
     var Data = { 
      getUnit: function() { 
       return unit; 
      }, 

      getFoo: function() { 
       return foo; 
      } 

      // some more functions... 
     } 
    }); 
} 

套接字:

channel.on('data', function (event) { 
    try { 
     event = JSON.parse(event);  
     // successCallback is what is given as second parameter in the `Service`.   
     $rootScope.$apply(successCallback(event)); 
    } catch (e) { 
     console.log('Error: ' + e); 
    } 
}); 

究竟應該如何共同努力?

  1. 插座更新進來,得到由Sockets對象
  2. Sockets呼叫其在Service
  3. 註冊回調函數在Service處理數據
  4. MISSING的處理的功能處理包裹在物體中的數據必須傳送到控制器
  5. MISSING只要有新更新,控制器就可以對數據執行任何操作。
  6. 該模板會自動更新。

任何人都可以幫我未命中部件?我嘗試了很多不同的方法,但每次都跑到死路一條。

+0

您是否嘗試過使用事件而不是回叫? – sdfacre

回答

0

你有沒有試過返回數據的承諾,然後$ state.reload()?

+0

承諾如何幫助我使用套接字更新?直到知道我只用於像'get'這樣的只能執行一次的請求。 – messy

0

得到它使用 '數據模型模式' 解決:

模板1(由控制器1中使用):

Status: {{unit.data.getStatus()}} 

模板2(通過控制器2中使用):

Status: {{foo.data.getBar()}} 

控制器1:

function ($scope, unitFactory) { 
    $scope.unit = unitFactory.getUnit(); 
} 

控制器2:

function ($scope, unitFactory) { 
    $scope.unit = unitFactory.getUnit(); 
    $scope.foo = unitFactory.getFoo(); 
} 

服務:

function(requestFactory) { 
    var unit = { data:{} }, 
     foo = { data:{} }; 

    Sockets.socket('unit', function (response) { 
     unit.data = new Unit(response['data']); 
     foo.data = new Foo(response['foo']); 
    }); 

    return     
     getUnit: function() 
      return unit; 
     }, 

     getFoo: function() { 
      return foo; 
     } 
     // some more functions... 
    } 
} 

套接字:

channel.on('data', function (event) { 
    try { 
     event = JSON.parse(event);  
     // successCallback is what is given as second parameter in the `Service`.   
     $rootScope.$apply(successCallback(event)); 
    } catch (e) { 
     console.log('Error: ' + e); 
    } 
}); 

由於數據被存儲在一個對象中的模板的數據被更新(因爲它是一個參考)。我必須習慣這些額外的屬性data,它看起來不錯,但它的工作。