AngularJS - $ watch无法正常工作

时间:2016-07-08 11:04:31

标签: angularjs websocket stomp sockjs

场景:集成Stomp与我们的Angular。在用户登录时,调用一个stomp服务,该服务发送数据然后在模块控制器中获取数据。

踩踏服务

select

模块控制器

var wrappedSocket = {

     init: function(url) {
      stompClient = Stomp.over(new SockJS(url));
     },
     connect: function(successCallback, errorCallback) {

      stompClient.connect({}, function(frame) {
          //$rootScope.$apply(function() {
          $timeout(function () {
        successCallback(frame);
          });
      }, function(error) {
          //$rootScope.$apply(function(){
          $timeout(function () {
        errorCallback(error);
          });
            });
     },
     subscribe : function(destination, callback) {
      stompClient.subscribe(destination, function(message,headers) {
          //$rootScope.$apply(function(){
          $timeout(function () {
          callback(message,headers);
          });
              }); 
     },
     send: function(destination, headers, object) {
      stompClient.send(destination, headers, object);
     }
   }

   return wrappedSocket;

这里svc是Sockjs var initializing = false; $timeout(function () { alert('timeout'); $scope.$watch(svc.getMessage, function (v) { if (initializing) { $timeout(function () { initializing = false; }); } else { if (v != '') { console.log(v); $scope.notifications = v; $scope.notification_count = $scope.notifications.length; } } }); }, 3000);

的一个实例

最终在服务中将svc.setMessage($scope.messages);更改为$rootScope.$apply(function() {。但后来在模块控制器中发现,$timeout(function () {无法工作/调用。

预期结果 - 应在$watch

内提取Stomp消息

发生了什么 - $ watch未被调用导致没有显示stomp消息。

  1. 如何在$watch内调用函数?
  2. 每次都有效的$scope.$watch(svc.getMessage, function (v)替代解决方案?

0 个答案:

没有答案
相关问题