share http.get data between factory and controller

2019-05-11 08:23发布

I succesfuly created a factory that gets a .php file output (JSON),

My question is how do I access it from wihtin the controller:

myApp = angular.module("myApp", [])

myApp.factory "mainData",  ($http) ->
 $http.get('gethome.php').success (data) ->
  data: data
  console.log(data)

myApp.controller "HomeCtrl", ($scope, mainData) ->
 $scope.home = mainData.data

Please let me know if Im choosing the right syntax here, I see lots of examples on how to create a module/controller everywhere in tutorials, and Im looking for the right way

2条回答
太酷不给撩
2楼-- · 2019-05-11 08:37

When injecting factories into Angular controllers, the injected factory reference contains those members that you've returned from the factory:

myApp.factory("mainData", function($http) {
  var mData = {};
  $http.get('gethome.php').success(function(data) {
    mData.data = data;
  });
  return mData;
});


myApp.controller("HomeCtrl", function($scope, mainData) {
  $scope.home = mainData.data; // Here mainData equals mData object literal from the mainData factory
});

But, the problem with your code is that mainData.data will always be undefined, because factory will return before the async $http request is completed. So instead, your factory should be returning a promise:

myApp.factory("mainData", function($http) {
  return $http.get('gethome.php');
});

myApp.controller("HomeCtrl", function($scope, mainData) {
  mainData.success(function(data) {
    $scope.home = data;
  });
});

Note: $http methods always return a promise by default.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-05-11 08:39

You can use this:

myApp.factory("mainData", function($http,$q) {
   var def =   $q.defer()
   $http.get('gethome.php').then(function(data){
       def.resolve(data)
   });
   return def.promise;
});

myApp.controller("HomeCtrl", function($scope, mainData) {
  mainData.then(function(data) {
    $scope.home = data;
  });
});
查看更多
登录 后发表回答