As I work on evaluating an expression within an if statement to return either true or false, I am utilizing $http promises. Despite the abundance of documentation available on this topic, I am confident in my ability to resolve any issues that may arise.
An interesting observation caught my attention: it appears that the .success callback is executing twice. When I check the console, I can see the output from the success callback appearing twice, indicating a duplicate log of "the call was a success". This led me to wonder why this repetition is occurring.
Upon reviewing the code, it seems that when save() triggers securityCheck.checkLogin(), it logs undefined initially as the promise hasn't been returned yet. Subsequently, the if statement evaluates to false, leading to the logging of "function returned false". Finally, the promise returns with "the call was a success" being logged once. But why does it show up twice in the console?
script
angular.module('login', ['security'])
.directive('loginDirective', ['$parse', 'securityCheck', function($parse, securityCheck) {
return {
scope: true,
link: function(scope, element, attrs, form) {
scope.save = function() {
console.log(securityCheck.checkLogin());
//evaluates to undefined, promise not returned yet
if (securityCheck.checkLogin()) {
console.log("function returned true");
} else {
console.log("function returned false");
}
}
}
};
}]);
angular.module('security', [])
.factory('securityCheck', ['$q', '$http', function ($q, $http) {
var security = {
checkLogin: function() {
$http.get('https://api.mongolab.com/api/1/databases/lagrossetete/collections/avengers?apiKey=j0PIJH2HbfakfRo1ELKkX0ShST6_F78A')
.success(function(data, status, headers, config) {
console.log('the call was a success!');
})
.error(function(data, status, headers, config) {
console.log('the call had an error.');
});
}
};
return security;
}]);
html
<html ng-app="login">
<body>
<login-directive ng-click="save()">click me</login-directive>
</body>
</html>
plnkr: http://plnkr.co/edit/tM7eHniDRvCLhzAw7Kzo?p=preview
Thanks!