share http.get data between factory and controller

烂漫一生 提交于 2019-12-07 14:16:14

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/17490561/share-http-get-data-between-factory-and-controller

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