2016-03-08 59 views
0

我可能完全困惑于如何正确使用角度回调方法调用ajax。我有以下角应用程序,并不能解决如何显示testUser对象只有在Ajax调用成功完成后。使用Angular Service进行异步HttpRequests - 如何回调?

我有一个NG控制器,就像这样:

Controllers.controller('mainController', ['$scope','UserService', function ($scope, UserService) { 
    ... 
    $scope.testUser = UserService.getTestUser(); 
    ... 
} 

的UserService的定义,像这样:

Services.service('UserService', function() { 
    ... 
    this.getTestUser = function() { 
    ... 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
     if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
     return JSON.parse(xmlhttp.responseText); 
     } 
    }; 
    xmlhttp.open('GET',url,false); //async set to false 
    xmlhttp.send(); 
    } 
    ... 
} 

目前,$ scope.testUser是 '不确定' 和空白的页面因为它在ajax调用完成之前显示。你可以在我的服务函数中看到我将async设置为false,但似乎并不重要。

我已经确认ajax调用最终会返回一个填充的用户对象。我错过了什么才能使页面显示$ scope.testUser只有当它被成功检索?

+1

有没有原因你使用xmlhttp而不是$ http? –

+1

使用AngularJS'$ http'服务来执行XHR。 https://docs.angularjs.org/api/ng/service/$http – georgeawg

+0

getTestUser方法不会返回任何内容,因此不分配任何内容。但如上面的评论所示,你应该使用$ http并返回一个承诺 –

回答

1

感谢Slava和georgeawg。我改变了以下,一切都很好!

Controllers.controller('mainController', ['$scope','UserService', function ($scope, UserService) { 
... 
UserService.getTestUser.async().then(function(testUser) { 
    $scope.testUser = testUser; 
}; 
... 
} 

而且在服务端我有这样的:

Services.service('UserService', function ($http) { 
... 
this.getTestUser = { 
    async: function() { 
    var promise = $http.get(url).then(function(response) { 
     return response.data; 
    }; 
    return promise; 
    } 
} 

谢谢!