AngularJS how to get actual factory's data in

2019-08-31 06:14发布

问题:

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;
});