tem*_*pid 18 angularjs angular-http
我刚开始学习Angular.js.如何在Angular.js中重写以下代码?
var postData = "<RequestInfo> "
+ "<Event>GetPersons</Event> "
+ "</RequestInfo>";
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == 4 || req.readyState == "complete") {
if (req.status == 200) {
console.log(req.responseText);
}
}
};
try {
req.open('POST', 'http://samedomain.com/GetPersons', false);
req.send(postData);
}
catch (e) {
console.log(e);
}
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所拥有的 -
function TestController($scope) {
$scope.persons = $http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.data = data; // how do pass this to $scope.persons?
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
Run Code Online (Sandbox Code Playgroud)
HTML
<div ng-controller="TestController">
<li ng-repeat="person in persons">{{person.name}}</li>
</div>
Run Code Online (Sandbox Code Playgroud)
我是朝着正确的方向吗?
Aja*_*wal 41
在当前的功能,如果你分配$scope.persons
到$http
这是一个承诺对象$http
返回一个承诺对象.
因此,不应分配scope.persons
给$ http,而应分配$scope.persons
内部成功,$http
如下所述:
function TestController($scope, $http) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.persons = data; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
Run Code Online (Sandbox Code Playgroud)
jpm*_*rin 13
这是Ajay beni给出的解决方案的变体.然后使用该方法允许链接多个promise,因为然后返回一个新的promise.
function TestController($scope) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
}
);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
95067 次 |
最近记录: |