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.