简介: 我在 $http 方法中遇到返回值问题,我了解如何在 $http.post 和 $http.get 方法中使用 $http,我无法在调用我的工厂的函数之外返回值。
我需要在 Controller 功能之外使用 $scope.historias 值。
我的 Angular 工厂: 第一工厂:
mediperbaricaApp.factory('listarTratamientos',['$http','$location','$q',
function($http, $location, $q){
var urlBase = host + 'index.php/';
var service = {};
console.log('DEBUG = entramos');
return {
response : function(response){
return $http({
url : (urlBase + 'tratamientos/getTratamientos'),
method : 'GET'
})
}
}
}]);
第二工厂:
mediperbaricaApp.factory('services', [ '$http' ,'$location', function(
$http, $location){
var urlBase = host + 'index.php/';
var service = {};
//listado de historias para el autocoplete del form
service.getHistorias = function(callback){
console.log('[DEBUG] FAC Listar Historias');
$http.get(urlBase + 'historias/getHistoria').
success(function(response){
return callback(response);
}).
error(function(response){
alert('Lo sentimos!, No se puede recuperar los datos, ' +
' intente mas tarde :(');
})
};
return service;
}]);
我的 Angular Controller Controller ,使用最后两个工厂,我得到相同的结果
mediperbaricaApp.controller('editController',function($scope,listarTratamientos,
$location,$routeParams, services){
console.log('[DEBUG] CTRL editar tratamientos');
//use first factory
$scope.datos = {};
services.getHistorias(function(response){
$scope.datos = response.data; // output array with data :)
})
//the data no exist in this place.
console.dir($scope.datos); //$scope.datos lost data :(
//use second factory
$scope.midata = {};
listarTratamientos.response().success(function(data){
$scope.midata = data;
console.dir($scope.midata); // output array with data :)
});
//data not exist in this place i dont understand
console.dir($scope.midata); //$scope.datos lost data :(
谢谢你的帮助! 注意。爱德华多
最佳答案
因此,在这部分中,您有一个回调函数,并且您尝试访问其下面的代码中的值:
services.getHistorias(function(response){
$scope.datos = response.data; // output array with data :)
})
//the data no exist in this place.
console.dir($scope.datos); //$scope.datos lost data output undefined variable :(
问题是回调函数是在该代码块之后执行的,因此您对该数据执行的所有操作都需要从该回调中调用,例如:
services.getHistorias(function(response){
$scope.datos = response.data; // output array with data :)
myFunction();
})
...
function myFunction() {
console.dir($scope.datos); //$scope.datos now available :)
}
其他代码块也是如此。
请记住有关回调/异步函数的这一点:仅仅因为一行代码位于另一行代码的正下方 - 这并不意味着它们会按该顺序执行。
<小时/>我现在将向您展示两个 super 简单的示例 - 一个错误的示例(就像您所做的那样),一个好的示例,使用 setTimeout 来模拟异步调用:
错误的
var data;
setTimeout(function() {
data = 'I will not be available!';
}, 100);
alert(data); // undefined
正确的
var data;
setTimeout(function() {
data = 'Que suerte!';
showAlert();
}, 100);
function showAlert(){
alert(data); // all good!
}
关于javascript - Angular $scope 在 Angular Controller 中的函数之外没有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31664355/