在工厂和控制器之间共享 http.get 数据 [英] share http.get data between factory and controller
问题描述
我成功地创建了一个获取 .php 文件输出 (JSON) 的工厂,
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
推荐答案
当将工厂注入 Angular 控制器时,注入的工厂引用包含您从工厂返回的那些成员:
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
});
但是,您的代码的问题在于 mainData.data 将始终未定义,因为工厂将在异步 $http 请求完成之前返回.因此,您的工厂应该返回一个承诺:
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;
});
});
注意:默认情况下,$http 方法总是返回一个 promise.
这篇关于在工厂和控制器之间共享 http.get 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!