Angularjs 无法将http在angular js中的响应数据存储到控制器中的局部变量并操作该变量?
来自json文件的http请求的FacoryAngularjs 无法将http在angular js中的响应数据存储到控制器中的局部变量并操作该变量?,angularjs,Angularjs,来自json文件的http请求的Facory myApp.factory('contactFactory', ['$http', function ($http) { var promise = $http.get('directiveJSON.json'); return promise; }]); 在controller中编写promise的t
myApp.factory('contactFactory', ['$http', function ($http) {
var promise = $http.get('directiveJSON.json');
return promise;
}]);
在controller中编写promise的then函数,现在我需要将promise2.data的值存储到局部变量x中,并对x执行一些操作。可能吗?现在console.log(x)将不包含响应数据
myApp.controller('MyCtrl',['$scope','contactFactory',function(scope,p) {
var x;
p.then(function(promise2) {
console.log(promise2.data);
scope.data=promise2.data;
x=promise2.data;
});
console.log(x);
}]);
是的,这是可能的。此代码甚至没有显示您正在尝试执行所要求的操作。console.log(x)中没有数据…如何访问该函数范围之外的响应数据语句
p。然后将该函数块放入回调,然后立即尝试使用console.log(x)
在将设置x
的回调返回之前使用数据。如何在控制器中的函数p.then()之外使用响应值。首选将其存储为变量x,以便我可以在我想要的地方之外使用x?在之内的任何事情。然后将在将来发生,在之外的任何事情现在都会发生。现在不能使用直到将来才有值的变量,JavaScript回调就是这样工作的。