📜 ⬆️ ⬇️

Deferred objects in AngularJS

Good time of day!

In this small post I want to tell about the use of Deferred AngularJS objects.

image
')

The mechanism of Deferred objects, or rather the idea was added from the library of Q Kris Koval. Its essence lies in the fact that if a function cannot return a value or an exception without blocking, then it returns a Promice object, which is an observer of the execution result. As soon as the result is obtained, or an error occurs at the time of receipt, the Deferred object notifies the observer about it.

Quite often, before loading the controller, it is necessary to obtain data for its operation. Speaking about data acquisition, I mean data that takes indefinite time. The most frequent case is receiving data from the application server. To solve this problem, we need to pass the resolve parameter to $ routeProvider when setting up application routing. A resolve is an object indicating a dependency of a controller. Once all dependencies are resolved, they are placed in the controller, after which the controller is further initialized.

More clearly this can be seen in the example.
angular.module('phonecat', ['phonecatFilters', 'phonecatServices', 'phonecatDirectives']). config(['$routeProvider', function($routeProvider) { $routeProvider. when('/phones', { templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl, resolve: PhoneListCtrl.resolve}). when('/phones/:phoneId', { templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl, resolve: PhoneDetailCtrl.resolve}). otherwise({redirectTo: '/phones'}); }]); 

 function PhoneListCtrl($scope, phones) { $scope.phones = phones; $scope.orderProp = 'age'; } PhoneListCtrl.resolve = { phones: function(Phone, $q) { var deferred = $q.defer(); //     //     deferred.resolve() //    deferred.reject() Phone.query(function(successData) { deferred.resolve(successData); }, function(errorData) { deferred.reject(); }); return deferred.promise; }, delay: function($q, $defer) { var delay = $q.defer(); $defer(delay.resolve, 1000); return delay.promise; } } 


In the above example, $ q.defer () creates an instance of the Defer object. This object has two methods, for returning a value - deferred.resolve (val) and returning a failure for any reason - deferred.reject (reason). The resolve or reject methods are called in callback methods that are called when data is received successfully or when an error occurs.
As soon as all Deferred objects are executed, their results are added to the controller, after that the route change event occurs and we can perform various actions with the data inside the controller.

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


All Articles