Search code examples
angularjsangular-promiseangular-http

AngularJS success function of promise


I have made a HTTP post API call to a URL.

I am getting the response, but I am confused how to write a success function, as there are many ways for it.

Here's my API call. Please help me how would the success function would be like?

var req = {
    method: 'POST',
    url: viewProfileurl,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + $rootScope.token,
    },
    params: {
        'action':'view'
    }
}

$http(req);

Solution

  • Angular uses promise internally in $http implementation i.e. $q:

    A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

    So, there are two options:

    1st option

    You can use the .success and .error callbacks:

    var req = {
      method: 'POST',
      url: viewProfileurl,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + $rootScope.token,
      },
      params: {
        'action': 'view'
      }
    
    }
    
    $http(req).success(function() {
        // do on response success
    }).error(function() {
    });
    

    But this .success & .error are deprecated.

    So, go for the 2nd option.

    2nd Option

    Use .then function instead

    var req = {
      method: 'POST',
      url: viewProfileurl,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + $rootScope.token,
      },
      params: {
        'action': 'view'
      }
    
    }
    
    $http(req).then(function() {
        // do on response success
    }, function() {
       // do on response failure
    });