AngularJS how to get actual factory's data in controller?

早过忘川 提交于 2020-01-17 12:51:25

问题


I have the factory, when i get socket messages. How i can get returned factory's actual data in my controller ? Help please.

app.factory('socket',['$rootScope', function($rootScope) {

    connection.open();

    var connection = new autobahn.Connection({
        url: 'wss://site.com:6555/',
        realm: 'realm'
    });

    var collection = {
       'topic1': [],
       'topic2': []
    };

  function onevent(args) {
      console.log("Event:", args[0]);
      collection.topic1.push(args[0]);
   }

  connection.onopen = function(session) {
   session.subscribe(userid, onevent);
  }

    return {
       collection: collection
    }

}]);

回答1:


The factory cannot push data to a controller, but the controller can pull from the factory. To do so, inject the factory into the controller:

app.controller('yourController', ['$scope', 'socket', function($scope, socket) {
    ...
    $scope.yourControllerCollection = socket.collection;
    ...
});

If you want the controller to auto-update when the socket factory receives an event and updates the collection, you can always inject the $rootScope into the factory and $emit an event that your controller can listen to. Something like:

app.factory('socket',['$rootScope', function($rootScope) {

   ...
   function onevent(args) {
      console.log("Event:", args[0]);
      collection.topic1.push(args[0]);
      $rootScope.$emit('SocketCollectionUpdated', collection); // Note that you can name your event whatever you want.
   }
   ...

}]);

app.controller('yourController', ['$rootScope', '$scope', 'socket', function($rootScope, $scope, socket) {
    ...
    $scope.yourControllerCollection = socket.collection;
    $rootScope.$on('SocketCollectionUpdated', function (event, data) {
        $scope.yourControllerCollection = data;
    });
    ...
});



回答2:


You want to inject the factory in the controller where you want to use the data. Here's a basic example of communicating data from factory to a controller.

app.factory('sharedData', function() {
 return {
  name: 'Daniel'
 };
});

Then in your controller you can simple set this data object from the factory to the $scope.

app.controller('MainController', function($scope, sharedData) {
 $scope.data = sharedData;
});

So in your case simply make a controller and inject the sockets factory, like this

app.controller('sockets', function($scope, sockets) {
 $scope.collection = collection;
});


来源:https://stackoverflow.com/questions/31565430/angularjs-how-to-get-actual-factorys-data-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!