I am trying to resolve a pair of ajax calls so that the data I need for the controller is available before it (and the directive it provides). However, the execution order works, and does not return the object I create, the result entered into my controller is the HTTP response object:
{ config: { … }, data: { … }, headers: { … }, status: 200 }
My code looks something like this:
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 really? Should the return value from $ http success actually be what $ http returns?
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 entered into my controller was undefined (I assume that $ http is asynchronous and resolve not blocked by $ http, so it returned before $ http was ready).
PS The synchronicity of $ http must be defined in the options object !!
Decision
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 the Ajay beniwal signpost and Mark Rajcok signpost .
PS then() documented on the $ q page .