IONIC没有从服务器接收套接字数据

时间:2016-04-05 01:10:10

标签: angularjs sockets ionic-framework meanjs

我在我的服务器上使用离子框架和我的服务器上的MEANJS。我正在使用Web套接字来获取实时数据。虽然每次在Android应用程序中发生CRUD时服务器端Web应用程序都会自动更新,但是当在服务器端进行更改时,Android应用程序不会自动更新。

Android App Service (AngularJS)

i

客户端控制器

.service('Socket', ['Authentication', '$state', '$timeout',
function (Authentication, $state, $timeout) {
    // Connect to Socket.io server
    this.connect = function () {
      // Connect only when authenticated
      if (Authentication.user) {
        this.socket = io('https://cryptic-savannah-60962.herokuapp.com');
      }
    };
    this.connect();

// Wrap the Socket.io 'on' method
this.on = function (eventName, callback) {
  if (this.socket) {
    this.socket.on(eventName, function (data) {
      $timeout(function () {
        callback(data);
      });
    });
  }
};

// Wrap the Socket.io 'emit' method
this.emit = function (eventName, data) {
  if (this.socket) {
    this.socket.emit(eventName, data);
  }
};

// Wrap the Socket.io 'removeListener' method
this.removeListener = function (eventName) {
  if (this.socket) {
    this.socket.removeListener(eventName);
  }
};
}

服务器控制器(NodeJS)

if (!Socket.socket && Authentication.user) {
  Socket.connect();
}

Socket.on('orderCreateError', function (response) {
  $scope.error = response.message;
});

Socket.on('orderCreateSuccess', function (response) {
  if ($scope.orders) {
    $scope.orders.unshift(response.data);
  }
});

Socket.on('orderUpdateSuccess', function (response) {
  if ($scope.orders) {
    // not the most elegant way to reload the data, but hey :)
    $scope.orders = Orders.query();
  }
});

1 个答案:

答案 0 :(得分:1)

您的服务器端有两个发射通道,但在客户端没有处理任何事件。

socket.io docs,您需要以下内容:

socket.on('orderUpdateSuccess', function (data) {
    // do something inside the app that will update the view
    console.log(data);
    Orders.update(data); // assuming you have a service called Orders to keep track of live data -- don't forget [$scope.$apply][2]
});

使用您的示例代码

Socket.on('orderUpdateSuccess', function (response) {
    if ($scope.orders) {
        $scope.$apply(function() {
            // not the most elegant way to reload the data, but hey :)
            $scope.orders = Orders.query();
        });
    }
});