Abel Abel - 5 months ago 14
AngularJS Question

controller and factory calling sequence differs while using $http?

I want to create a simple login, so I just created a html page with username and password. I created a controller and called a function called login and inside that I called a factory which returns a factory data, and I would create login based on that data.

Controller

myApp.controller('login', ['$scope','$rootScope', '$location', '$window', 'authenticate', '$http', '$cookieStore',function($scope, $rootScope, $location, $window, authenticate, $http, $cookieStore) {
$scope.alert = '';
$scope.login = function(){
authenticate.login($scope.login.username, $scope.login.password).then(function(response){
alert("Inside controller"+JSON.stringify(response));
});
}
}]);


My factory

myApp.factory('authenticate',['$http', '$filter', '$cookieStore', '$rootScope', '$window', '$q',
function($http, $filter, $cookieStore, $rootScope, $window, $q) {
var data = "";
var deferred = $q.defer();
return {
login: function(userName,password){
$http.post('user/serverside/authentication.php',{username: userName, password: password})
.then(function(response){
deferred.resolve(response.data);
alert("FACTORY"+JSON.stringify(response));
});
return deferred.promise;
}
}
}]);


I call the login function inside the controller on login,
The issue is when I logged in for


  • The first time with one data as expected first alert inside factory
    executed and then the alert inside the controller is executed.

  • But on the second time alert inside controller executed first and the
    factory alert displaying,



Doubts


  1. Why the execution sequence change in the second time?

  2. Is this a right way to use for login, if any better ways please
    suggest?


Answer

I think the mistake its beacuse u should generate promise in every function and no in the main factory like:

myApp.factory('authenticate',['$http', '$filter', '$cookieStore', '$rootScope', '$window', '$q',
function($http, $filter, $cookieStore, $rootScope, $window, $q) {
    var data = "";

    return {
        login: function(userName,password){
            var deferred = $q.defer();
            $http.post('user/serverside/authentication.php',{username: userName, password: password})
            .then(function(response){
                deferred.resolve(response.data);
                alert("FACTORY"+JSON.stringify(response));
            });
            return deferred.promise;
        }
    }
}]);

Ur code not works because promise its generated first time executed and when code checked if promise its resolve automatically execute then block.

2.- You can use ssl to securize your login, but the function login its similar. The important its implementation its on server side.

Comments