2016-04-07 50 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,它看起来不错,但它的工作。