我刚开始学习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);
}
这是我到目前为止所拥有的 -
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;
});
}
HTML
<div ng-controller="TestController">
<li ng-repeat="person in persons">{{person.name}}</li>
</div>
我是朝着正确的方向吗?
答案 0 :(得分:41)
在当前函数中,如果要将$scope.persons
分配给$http
,这是一个承诺对象,$http
将返回一个承诺对象。
因此,您应该在scope.persons
的成功中分配$scope.persons
,而不是将$http
分配给$ 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;
});
}
答案 1 :(得分:13)
以下是 Ajay beni 给出的解决方案的变体。使用然后方法可以链接多个承诺,因为然后会返回一个新的承诺。
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
}
);
}
答案 2 :(得分:0)
使用$ http:
$http.post(url, data, [config]);
实施例:
$http.post('http://service.provider.com/api/endpoint', {
Description: 'Test Object',
TestType: 'PostTest'
}, {
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
).then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});
让我们打破这个:Url有点明显,所以我们跳过它......
数据:这是邮递员请求的正文内容
{
Description: 'Test Object',
TestType: 'PostTest'
}
config:这是我们可以注入标题,事件处理程序,缓存的地方......请参阅AngularJS: API: $http: scroll down to config标题是人们在angularJS中难以复制的最常见的http邮递变体
{
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
响应:$ http操作返回一个有角度的承诺,我建议使用.then(successFunction,errorFunction)来处理该承诺,请参阅AngularJS: The Deferred API (Promises)
.then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});