AngularJS includes a service based on Promises to allow for asynchronous functions, called $q. As the getTestimonials function includes an asynchronous request, we need to make the function itself asynchronous. To do this, first we add a dependency on $q to testimonialsService. We then create a deferred object, which will resolve when the HTTP request succeeds, or reject when the request fails.
Finally, we return a Promise, which will eventually resolve:
angular.module('MyPhoto') //Declare the service and any dependencies, attaching // it to the MyPhoto module.. .service('testimonialsService', function($http, $q) { function getTestimonials() { //Create the deferred object var deferred = $q.defer() //Use $http.get to create a promise to load
//testimonials.json $http.get('/data/testimonials.json') //Call the then method of the promise .then( //Define what happens if the promise returns // successfully function(success) { //Resolve the deferred and return the data // property of the success object deferred.resolve(success.data) }, //Define what happens if the promise returns an //error function(error) { //Reject the deferred, returning the error //value deferred.reject(error) } ) //Return the deferred promise return deferred.promise } return { getTestimonials: getTestimonials } })
Now our function returns a Promise, which will resolve to either the data part of our success object, or reject and return the error object. The usage of getTesimonials will now be something like:
testimonialsService.getTestimonials() .then( function(response) { console.log(response) }, function(error) { console.error(error) } )
What is happening here is self-explanatory. We call the getTestimonials function of testimonialsService. The getTestimonials function has a then property. We pass two functions to then: the first function takes the successful response as a parameter and defines what to do when the Promise resolves; the second function takes the rejected response and defines what to do when the Promise is rejected. Now that we have a service that will return the list of testimonials, let's create an AngularJS directive to render the component.