javascript - AngularJS: $routeProvider when resolve $http returns response obj instead of my obj -
i'm trying resolve couple ajax calls data controller needs available before (and directive furnishes) execute. order of execution working, however, instead of returning object create, result injected controller $http's response object:
{ config: { … }, data: { … }, headers: { … }, status: 200 }
my code 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 daft? shouldn't return value $http's success returned $http?
i 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 data
object injected controller undefined (i'm guessing because $http asynchronous , resolve
not blocked $http—so returned before $http ready).
p.s. synchronicity of $http should definable in 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 ajay beniwal's pointer , mark rajcok's pointer.
p.s. then()
documented on $q's page.
$http @returns {httppromise} returns {@link ng.$q promise} object standard
then
method , 2 http specific methods:success
,error
.then
method takes 2 arguments success , error callback called response object.success
,error
methods take single argument - function called when request succeeds or fails respectively. arguments passed these functions destructured representation of response object passedthen
method. response object has these properties:
Comments
Post a Comment