AngularJS handles rejected response using UI-Router

I have a service that transfers my API calls to Angular:

var ConcernService = { list: function (items_url) { var defer = $q.defer(); $http({method: 'GET', url: api_url + items_url}) .success(function (data, status, headers, config) { defer.resolve(data, status); }) .error(function (data, status, headers, config) { defer.reject(data, status); }); return defer.promise; }, 

Then my application configuration with UI-Router :

  .config(function($stateProvider){ $stateProvider .state('default', { url: '/', resolve: { tasks: function ($stateParams, ConcernService) { return ConcernService.list('tasks/').then( function (tasks) { return tasks; }, function (reason) { return []; } ); }, ... } } }); 

This is the simplest configuration I could handle, which basically just returns an empty object if it encounters 403 , 404 , etc., and I can handle this in the view template.

My question is: what is the best approach for getting other details to the view / template, e.g. rejecting reason and status . Should it be returned to the tasks object or separately?

Any help is greatly appreciated.

+6
source share
1 answer

Well, firstly, your first bit of code has a pending anti-pattern , let me fix it:

 list: function (items_url) { return $http.get(api_url + items_url); // $http already returns a promise }, 

Also note that deferred deviations and executions are one value, so your multiple return values ​​really don't work here.

Now let's look at the router. First of all, your first execution handler is superfluous.

 .state('default', { url: '/', resolve: { tasks: function ($stateParams, ConcernService) { return ConcernService.list('tasks/'); // result.data contains the data here }, ... } 

Now the problem that we have here is what happens in case of a deviation?

Ok, listen to $stateChangeError :

 $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){ ... }) 

Here you can listen to the failure of state changes from failures.

+7
source

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


All Articles