I don't know what is the exactly difference between AngularJS $q
service and simply using .then()
after async request.
Simple example with .then()
:
function InboxService($http) {
this.getEmails = function getEmails() {
return $http.get('/emails');
};
}
And when using the service (just part of code):
InboxService.getEmails()
.then(function (response) {
// use response
});
What is the difference with $q
service with resolve and reject ?
What is the difference with $q service with resolve and reject ?
I assume you are asking about the usage of var deferred = $q.defer()
with subsequent deferred.resolve()
or deferred.reject()
? In this case, the answer is that you don't need it since you already have a promise object returned by $http
service. In fact, manually constructing another new promise with $q
is not recommended and considered an anti-pattern.
In cases where you work with asynchronous functions (timeouts, ajax-requests) that are not already wrapped into promise, then this is a case when you might want to use $q
to create and return promise. But once again, in your case you don't need it as $http
service constructs promise for you and one more is simply redundant.
The $q is superfluous and in most cases is not needed. http://www.codelord.net/2015/09/24/$q-dot-defer-youre-doing-it-wrong/