18

I've just started learning Angular.js. How do I re-write the following code in 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);
    }

Here's what I have so far -

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 I in the right direction?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
tempid
  • 7,838
  • 28
  • 71
  • 101

3 Answers3

41

In your current function if you are assigning $scope.persons to $http which is a promise object as $http returns a promise object.

So instead of assigning scope.persons to $http you should assign $scope.persons inside the success of $http as mentioned below:

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

}
yarl
  • 3,107
  • 1
  • 22
  • 28
Ajay Beniwal
  • 18,857
  • 9
  • 81
  • 99
  • Thanks, I have tried so many solutions but headers: `{'Content-Type': 'application/x-www-form-urlencoded'}` did the trick – Stefan Walther Jun 01 '14 at 22:19
  • 2
    Please note that the `success` and `error` functions have deprecated now. – Ali Dec 07 '15 at 12:57
  • See [Why are angular $http success/error methods deprecated? Removed from v1.6?](http://stackoverflow.com/questions/35329384/why-are-angular-http-success-error-methods-deprecated-removed-from-v1-6/) – georgeawg Mar 15 '17 at 12:34
13

Here is a variation of the solution given by Ajay beni. Using the method then allows to chain multiple promises, since the then returns a new 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
        }
    );
}
jpmorin
  • 6,008
  • 2
  • 28
  • 39
0

use $http:

AngularJS: API: $http

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

Implementation example:

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

Lets break this down: Url is a little obvious, so we skip that...

  1. data: This is the body content of your postman request

    {
        Description: 'Test Object',
        TestType: 'PostTest'
    }
    
  2. config: This is where we can inject headers, event handlers, caching... see AngularJS: API: $http: scroll down to config Headers are the most common postman variant of http that people struggle to replicate in angularJS

    {
        headers {
            'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
            'Accept': 'application/json;odata=verbose'
        }
    }
    
  3. Response: the $http actions return an angular promise, I recommend using .then(successFunction, errorFunction) to process that promise see AngularJS: The Deferred API (Promises)

    .then(function (result) {
        console.log('Success');
        console.log(result);
    }, function(error) {
        console.log('Error:');
        console.log(error);
    });
    
Chris Schaller
  • 13,704
  • 3
  • 43
  • 81