How to handle nested services and promises with permission and $ routeChangeError

This is more like the research I did while playing with AngularJS, and I would like to share what I think some people might find this useful.

Sometimes you need to get some data from several services before creating an instance of the controller and displaying the view.

A situation may also arise when a particular service expects a response from another service - a kind of nested service structure.

In addition, you want to make sure that if any of these services fail, you will handle the error accordingly.

+4
source share
1 answer

The myApp module must have services called myFirstService and mySecondService .

If you refuse any services, rejecting it:

 defer.reject("second Service Failed"); 

The $routeChangeError event is $routeChangeError , and the message is displayed to the user in the console.

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>myApp</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"> </script> <script> var myApp = angular.module('myApp', []); myApp.config(function($routeProvider){ $routeProvider .when('/', { controller: 'ViewCtrl', templateUrl: 'view/app.html', resolve: { loadData: function(myFirstService){ return myFirstService.start(); } } }) }); var appCtrl = myApp.controller('AppCtrl', function($scope, $rootScope){ $rootScope.$on('$routeChangeError', function(event, current, previous, rejection){ console.log('Some service has failed: ', rejection); }); }); var viewCtrl = myApp.controller('ViewCtrl', function($scope, $route){ $scope.feedback = { message: 'All the services are working!' } }); myApp.factory('myFirstService', ['$q', '$timeout','mySecondService', function($q, $timeout, mySecondService) { var defer = $q.defer(); return { start: function() { $timeout(function(){ defer.resolve('FIRST Service \'myFirstService\' Failed'); }, 2000); return mySecondService.start().then(function(){ return defer.promise }); } } }]); myApp.factory('mySecondService', ['$q', '$timeout', function($q, $timeout) { var defer = $q.defer(); return { start: function() { $timeout(function(){ defer.resolve("second Service Failed"); }, 2000); return defer.promise; } } }]); </script> </head> <body ng-app="myApp" ng-controller="AppCtrl"> <script id="view/app.html" type="text/ng-template"> <h1>{{ feedback.message }}</h1> </script> <div ng-view></div> </body> </html> 
+2
source

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


All Articles