AngularJS: $routeProvider when resolve $http retur

2019-05-03 11:41发布

问题:

I'm trying to resolve a couple ajax calls so that data my controller needs is available before it (and a directive it furnishes) execute. The order of execution is working, however, instead of returning the object I create, the result injected into my controller is $http's response object:

{
  config: { … },
  data: { … },
  headers: { … },
  status: 200
}

My code essentially looks like:

app.config([
  '$routeProvider', function($routeProvider)
  {
    $routeProvider
      .when('/path', {
        …,
        "resolve": {
          "data": [
            '$http',
            function($http)
            {
              return $http
                .get('/api/data')
                .success(function(data,status) { return data.rows[0]; })
                .error(function(data,status)   { return false; });
            }
          ]
        }
      });
  }
]);

Am I daft? Shouldn't the return value from $http's success actually be what is returned by $http?

I also tried

…
"resolve": {
  "data": [
    '$http',
    function($http)
    {
      var response;
      $http
        .get('/api/data')
        .success(function(data,status) { response = data.rows[0]; })
        .error(function(data,status)   { response = false; });
      return response;
    }
  ]
}

But then the data object injected into my controller was undefined (I'm guessing because $http is asynchronous and resolve was not blocked by $http—so it returned before $http was ready).

P.S. The synchronicity of $http should be definable in its options object!!

Solution

app.config([
  '$routeProvider', function($routeProvider)
  {
    $routeProvider
      .when('/path', {
        …,
        "resolve": {
          "data": [
            '$http',
            function($http)
            {
              return $http
                .get('/api/data')
                .then(
                  function success(response) { return response.data.rows[0]; },
                  function error(reason)     { return false; }
                );
            }
          ]
        }
      });
  }
]);

Thanks to Ajay beniwal's pointer and Mark Rajcok's pointer.

P.S. then() is documented on $q's page.

回答1:

$http @returns {HttpPromise} Returns a {@link ng.$q promise} object with the standard then method and two http specific methods: success and error. The then method takes two arguments a success and an error callback which will be called with a response object. The success and error methods take a single argument - a function that will be called when the request succeeds or fails respectively. The arguments passed into these functions are destructured representation of the response object passed into the then method. The response object has these properties: