【问题标题】:$http post in Angular.jsAngular.js 中的 $http 帖子
【发布时间】:2013-04-09 06:20:44
【问题描述】:

我刚刚开始学习 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>

我的方向正确吗?

【问题讨论】:

    标签: angularjs angular-http


    【解决方案1】:

    在您当前的函数中,如果您将$scope.persons 分配给$http,这是一个promise 对象,因为$http 返回一个promise 对象。

    因此,与其将scope.persons 分配给$http,不如在$http 的成功中分配$scope.persons,如下所述:

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

    【讨论】:

    【解决方案2】:

    这是 Ajay beni 给出的解决方案的变体。使用方法 then 允许链接多个 Promise,因为 then 返回一个新的 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
            }
        );
    }
    

    【讨论】:

      【解决方案3】:

      使用 $http:

      AngularJS: API: $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 有点明显,所以我们跳过它...

      1. 数据:这是您的邮递员请求的正文内容

        {
            Description: 'Test Object',
            TestType: 'PostTest'
        }
        
      2. config:这是我们可以注入标头、事件处理程序、缓存的地方...见AngularJS: API: $http: scroll down to config标头是人们难以在 angularJS 中复制的最常见的 http 邮递员变体

        {
            headers {
                'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
                'Accept': 'application/json;odata=verbose'
            }
        }
        
      3. 响应:$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);
        });
        

      【讨论】:

        最近更新 更多