Question:

How would you make an Angular service return a promise? Write a code snippet as an example

Answer:

To add promise functionality to a service, we inject the “$q” dependency in the service, and then use it like so:

angular.factory('testService', function($q){
	return {
		getName: function(){
			var deferred = $q.defer();

			//API call here that returns data
			testAPI.getName().then(function(name){
				deferred.resolve(name)
			})

			return deferred.promise;
		}
	}
})

The $q library is a helper provider that implements promises and deferred objects to enable asynchronous functionality

Source: https://docs.angularjs.org/api/ng/service/$q


Keywords:

© 2017 QuizBucket.org