AngularJS Essentials
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Dependency Injection and Services<br />
The deferred API<br />
In order to create a new promise, we need to inject the $q service into our component<br />
and call the $q.defer() function to instantiate a deferred object. It will be used to<br />
implement the asynchronous behavior in a declarative way through its API. Some of<br />
the functions are as follows:<br />
• resolve(result): This resolves the promise with the result.<br />
• reject(reason): This rejects the promise with a reason.<br />
• notify(value): This provides updated information about the progress of<br />
the promise. Consider the following code snippet:<br />
services.js<br />
parking.factory('carSearchService', function ($timeout, $q) {<br />
var _filter = function (cars, criteria) {<br />
var deferred = $q.defer();<br />
$timeout(function () {<br />
var result = [];<br />
angular.forEach(cars, function (car) {<br />
if (_matches(car, criteria)) {<br />
result.push(car);<br />
}<br />
});<br />
if (result.length > 0) {<br />
deferred.resolve(result);<br />
} else {<br />
deferred.reject("No results were found!");<br />
}<br />
}, 1000);<br />
return deferred.promise;<br />
};<br />
var _matches = function (car, criteria) {<br />
return angular.toJson(car).indexOf(criteria) > 0;<br />
};<br />
return {<br />
filter: _filter<br />
}<br />
});<br />
[ 100 ]<br />
www.it-ebooks.info