在工厂和控制器之间共享http.get数据 [英] share http.get data between factory and controller

查看:161
本文介绍了在工厂和控制器之间共享http.get数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我成功创建了一个获取.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将始终未定义,因为工厂将返回在async $ 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方法默认返回一个承诺。

这篇关于在工厂和控制器之间共享http.get数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆