The use of $q in that situation isn't really needed. You could do something
like
authenticate: function (url, user) {
return $http.post(url,user).then(function(response){
console.log(response);
return response;
});
}
That will return a promise that console.logs its response and still
resolves to that response. You can delete the .then entirely. Either way,
in your application logic you could do:
AuthenticateService.authenticate(url,user).then(function(response) {
//note that this is the 'success' state
$scope.view.username = response.data.username;
//etc etc
}).catch(function(err) {
// the $post returned a non 200 value
console.log('ERROR authenticating!');
console.log(err);
});
Of course, just having a function that returns a $http.post is a bit of an
over-abstraction. You could just put the $http on your controller too. On
the other hand, most of the time you're not *just* doing the $http.post in
the authenticate service. You could modify that to do
authenticate: function(user) {
//we can keep the service URL local so it's only changed in one place
return $http.post(knownBackendUrl,user).then(function(response) {
//deal with response.data here and create a
// user object to return that's more abstracted
}).catch(function(err) { // also do error handling
});
Then it's more worthwhile.
On Tue Nov 25 2014 at 3:28:12 AM Houssem Yahiaoui <[email protected]>
wrote:
> Hello,
> i have this thing in my *code* that i include *$q* with *$http* ..
>
> *authenticate : function(url, user){*
> * var defer = $q.defer();*
> * //console.log('here');*
> * return $http.post(url, user).then(function (response) {*
> * if (response.data) {*
> * console.log(response);*
> * defer.resolve(response);*
> * } else{*
> * defer.resolve(response.data.errMessage);*
> * }*
> * return defer.promise;*
> * });*
>
> * }*
>
> and it works normally and i know that* $http* resolve automatically a
> *promise* .. so is the usage of *$q promise* here is needed ?
>
> --
> You received this message because you are subscribed to the Google Groups
> "AngularJS" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To post to this group, send email to [email protected].
> Visit this group at http://groups.google.com/group/angular.
> For more options, visit https://groups.google.com/d/optout.
>
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.