var myApp = angular.module('myRealApp',[]);
myApp.controller('myController',function($scope,$http){
"use-strict";
$scope.content = [];
$scope.fetchContent = function () {
$http({
method : 'POST',
ContentType : "application/json",
url : "http://localhost:8080/myUrl",
headers : { 'Content-Type' : 'application/json'}
})
.success(function(response){
$scope.content = response;
console.log($scope.content); //Shows the returned object from server
});
}
$scope.fetchContent();
console.log($scope.content); //Shows as []
}
当我加载页面时,$scope。fetchContent被调用并从服务器获取数据,并将其分配给$scope.content。但是,当我访问$scope。在这个函数之外的内容,它仍然显示它的值为[]。我在这里做错了什么?
从服务器返回的数据是对象列表。
$http是异步的。进程的顺序如下:
-> fetchContent()
-> console.log($scope.content) // outside of your $http
-> $http.success
内容无论如何都会显示在你的html模板中,因为angular正在监视你的作用域,所以不用担心。如果您想在获取数据后运行另一个进程,请在成功回调函数
$http
创建一个承诺,该承诺将在对http://localhost:8080/myUrl
的ajax调用被解析时被解析。当浏览器到达console.log($scope.content);
行(在承诺创建后的几行)时,承诺还没有被解析。
如果你想做的东西(如console.log
),当你的承诺是解决外的的.success()
,你必须得到承诺,并使用.then()
的承诺$http
已经创建如下:
"use-strict";
var myApp = angular.module('myRealApp',[]);
myApp.controller('myController',function($scope,$http){
$scope.content = [];
$scope.fetchContent = function () {
return $http({ //line changed
method : 'POST',
ContentType : "application/json",
url : "http://localhost:8080/myUrl",
headers : { 'Content-Type' : 'application/json'}
});
}
var promise = $scope.fetchContent();
promise.then(function() { //line changed
console.log($scope.content);
});
}
- 边注:你应该把
"use-strict";
行放在文件的顶部 - 边注²:注意像这样创建控制器:
myApp.controller('myController', function($scope,$http) { ... })
将在最小化时创建错误,更喜欢冗余版本:myApp.controller('myController', ["$scope", "$http", function($scope,$http) { ... }])