2013-04-09 9 views
17

Tôi vừa mới bắt đầu học Angular.js. Làm cách nào để viết lại mã sau trong 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); 
    } 

Dưới đây là những gì tôi có cho đến nay -

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> 

Am tôi đi đúng hướng?

Trả lời

41

Trong chức năng hiện tại của bạn nếu bạn đang chỉ định $scope.persons đến $http là đối tượng lời hứa là $http trả về đối tượng lời hứa.

Vì vậy, thay vì gán scope.persons đến $ http bạn nên gán $scope.persons bên trong sự thành công của $http như đã đề cập dưới đây:

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; 
      }); 

} 
+0

Cảm ơn bạn rất nhiều. Nó hoạt động hoàn hảo. – tempid

+0

Cảm ơn, tôi đã thử rất nhiều giải pháp nhưng tiêu đề: '{'Content-Type': 'application/x-www-form-urlencoded'}' đã làm thủ thuật –

+2

Xin lưu ý rằng các hàm 'success' và' error' có không được dùng nữa. – Ali

13

Đây là một biến thể của giải pháp do Ajay beni. Sử dụng phương pháp sau đó cho phép kết chuỗi nhiều lời hứa, vì sau đó trả về lời hứa mới.

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 
     } 
    ); 
} 
0

sử dụng $ http:

AngularJS: API: $http

$http.post(url, data, [config]); 

dụ thực hiện:

$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); 
}); 

Cho phép phá vỡ này xuống: Url là một chút rõ ràng, vì vậy chúng tôi bỏ qua .. .

  1. dữ liệu: Đây là nội dung cơ thể của yêu cầu đưa thư của bạn

    { 
        Description: 'Test Object', 
        TestType: 'PostTest' 
    } 
    
  2. cấu hình: Đây là nơi chúng ta có thể bơm tiêu đề, xử lý sự kiện, bộ nhớ đệm ... see AngularJS: API: $http: scroll down to config Headers là những biến thể đưa thư phổ biến nhất của http rằng những người đấu tranh để tái tạo trong angularJS

    { 
        headers { 
         'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==', 
         'Accept': 'application/json;odata=verbose' 
        } 
    } 
    
  3. đáp ứng: các $ hành động http trả về một lời hứa góc, tôi khuyên bạn nên sử dụng .Sau đó (successFunction, errorFunction) để quá trình hứa hẹn thấy AngularJS: The Deferred API (Promises)

    .then(function (result) { 
        console.log('Success'); 
        console.log(result); 
    }, function(error) { 
        console.log('Error:'); 
        console.log(error); 
    });