I have a login form that uses the promise object for authentication. Everything works smoothly except when the form validation is triggered. Below is my HTML code:
<form id="signin" class="signinform" autocomplete="off">
<span ng-show="errorName" class="error_block">{{ errorName }}</span>
<input placeholder="User Name" ng-model="user.name" type="text" name="user_name" required>
<input placeholder="Password" ng-model="user.password" type="password" name="password" required>
<input type="submit" ng-click="submit(user)" value="Log IN" id="submit">
</form>
The controller with the ng-click function is shown below:
$scope.submit = function(user){
LoginService.login(user)
.then(function(response) {
var userInfo = response.userName
$rootScope.$emit('myEvent',userInfo);
$location.path("/details/1");
},
function(error) {
$scope.errorName = "Invalid Username or Password";
});
}
This is the factory service:
app.factory("LoginService", function($http, $q, $window) {
var userInfo;
var deferred = $q.defer();
function login(user) {
$http({
method: 'POST',
url: "login.php",
data: { "userName": user.name, "password": user.password },
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
}).then(function(result) {
userInfo = {
accessToken: result.data.login.token,
userName: result.data.login.name
};
$window.sessionStorage["userInfo"] = JSON.stringify(userInfo);
deferred.resolve(userInfo);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
return {
login: login
};
});
If the login fails due to incorrect credentials, an error message will be displayed. However, even after entering correct credentials, you may not be redirected to the details page and still see the same error message. But upon refreshing the page, you are already logged in. This issue seems to be related to the execution of the `then` function in the `$scope.submit`. I have tried various methods like `scope.apply` but haven't found a solution yet. Any help would be appreciated.