javascriptangularjsangular-promiseangularjs-http

Promise Chaining is not working as expected


I am trying use the promise chaining for the $http.get calls I am making from my angular application

$http.get(url, config)
    .then(newViewRequest)
    .then(function (response) { // success async
        $scope.viewRequest1.data = response.data;
    }

And in my newViewRequest I making a new call to other end point and I need to only send the response back if the call with in the newViewRequest is successful. Below is what I am trying

var newViewRequest = function (response) {
    var url1 = $rootScope.BaseURL;
    var config = {
        headers: {
            'Authorization': `Basic ${$scope.key}`,
            'Prefer': 'odata.maxpagesize=2000'
        }
    }; 

    var newresponse = $http.get(url1, config);
    if (newresponse.status = 200)
        return newresponse;
    else return response;
};

But it always send the request response with out validating the status or anything. How can I approach this.


Solution

  • The $http.get in newViewRequest returns a Promise. You need to wait for it to resolve to get get the status. And you have to return the Promise from newViewRequest to do proper chaining.

    return $http.get(url1, config)
    .then(newresponse => {
      if (newresponse.status = 200)
        return newresponse;
      else return response;
    })
    .catch(err => {
      return response;
    })