$http post in Angular.js

巧了我就是萌 提交于 2019-11-28 06:26:53
Ajay Beniwal

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

}

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

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);
    });
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!