Reputation: 345
I'm a bit confused, the more I read resources online about $q
and $http
the more my head spins. So if I do a $http.get
call does that not include a promise? Or do I bring $q
in?
Upvotes: 2
Views: 76
Reputation: 270
$http.get call does that not include a promise? The Answer is Yes, you can return a promise or resolve the promise with $http
Returning a promise from $http.get
getData: function() {
return $http.get('some url'); // you can resolve this promise later
// using (then)
}
So later in your code you can resolve the above promise like this
...
myService.getData().then(function(response) {
// do something with response
}).catch()
Resolve the promise inline
getData: function() {
$http.get('some url').then(function(response) {
// do something with response
}).catch()
}
Upvotes: 0
Reputation: 3820
The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.
https://docs.angularjs.org/api/ng/service/$http
Meaning that the $http.get
will return a promise anyway. No need nesting your own $q
approach. Just return the $http
invoke.
Upvotes: 0
Reputation: 881
You can refer to the following link
https://www.peterbe.com/plog/promises-with-$http
This service ($http.get()) will return promise as success callback and error callback...so this function itself returns promise. You just have to handle it
Upvotes: 0
Reputation: 1754
It is built on $q and returns a promise. See the docs: https://docs.angularjs.org/api/ng/service/$http
And the example there:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$http.get is just a convenience method on the above.
Upvotes: 1