AngularJS: $ routeProvider when resolving $ http returns obj response instead of my obj

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 .

+4
source share
1 answer

$ http @returns {HttpPromise} Returns the object {@link ng. $ q prom} with the standard then method and two special http methods: success and error . then method takes two arguments for success and an error callback that will be called using the response object. The success and error methods take one argument - the function that will be called when the request is successful or unsuccessful, respectively. The arguments passed to these functions are a destructive representation of the response object passed to then . The response object has the following properties:

+2
source

Source: https://habr.com/ru/post/1491944/


All Articles