V
V
Valeriy Donika2015-10-24 00:57:13
Angular
Valeriy Donika, 2015-10-24 00:57:13

Using a service in a then() controller?

Hello. I can't figure it out.
There is an auth controller and there is a service
. I send the form to the server and get successful data, etc. But swears TypeError: Cannot read property 'then' of undefined.
Controller code

$scope.login = function(){
                    authService.login($rootScope.user).then(
                        function(response){
                            if(response.data.state === 'success'){
                                $cookies.putObject('user', response.data.user, {expires: expireDate});
                                $rootScope.authenticated = true;
                                $rootScope.current_user = response.data.user.username;
                                $location.path('/');
                            }
                            else{
                                $rootScope.error_message = response.data.message;
                            }
                        },
                        function(response){
                            $rootScope.error_message = "Some error with register" + response.data.status;
                        }
                    );
                };

and service
authService.login = function(data){
              $http.post('/auth/login', data).then(function(response){
                    return response;
                }, function(response){
                    
                });
            };

I thought that then would be executed in the service first and only then it would give the controller a response. But in reality it turns out differently.
Tell me what I'm doing wrong.
Ps I googled and came across promises, etc. I don't quite know how to use them.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Radiks Alijevs, 2015-10-24
@dedalik

You need to do a return:

return $http.post('/auth/login', data).then(function(response){ ...

V
Valeriy Donika, 2015-10-24
@Valonix

That's how it worked

authService.login = function(data){
                var deferred = $q.defer();
                $http.post('/auth/login', data).then(function(response){
                    setTimeout(function() {
                        if(response.data){
                            deferred.resolve(response);
                        }else {
                            deferred.reject('err');
                        }
                    },1000);
                });
                return deferred.promise;
            };

It's in the service.
ps So always, you sit for 2 hours, racking your brains, posting on the toaster. And then bam and it works :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question