Angular JS - The controller function does not return after executing the service script

The login process for my app is functioning correctly. It successfully connects to the server and returns a 200 Status, indicating that it is working fine. However, after the service completes its task, the controller does not execute its lines of code:

Controller:

 loginService.signin(formData, function(res) {
     console.log('This message never prints');
 });

Any ideas on how to resolve this issue? It's possible that the interceptor may be causing this behavior. Here are the relevant scripts:

app.js

'use strict';

var app = angular.module('myapp', [
'ngRoute',
'ngStorage',
'ngCookies',
'myapp.controllers',
'myapp.services'
]);

app.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {

    $routeProvider
        .when('/', {
            templateUrl: 'views/logueo.html',
            controller: 'LoginController'
        })
        .when('/principal', {
            templateUrl: 'views/principal.html'
        })
        .otherwise({
            redirectTo: '/'
        });
}]);

controller.js

angular.module('myapp.controllers', [])

    .controller('LoginController', 
        ['$rootScope', 
        '$scope', 
        '$http', 
        '$location', 
        '$localStorage', 
        'loginService',
        '$cookies',
        function ($rootScope, $scope, $http, $location, $localStorage, loginService, $cookies) {

        $scope.signin = function() {

            var formData = {
                username: $scope.username,
                password: $scope.password
            };

            loginService.signin(formData, function(res) {

                // ISSUE HERE.
                // IT DOES NOT EXECUTE THE REMAINING LINES.

                // Incorrect user.
                if (res.type == false) {
                    console.log("FALSE " + res.data);

                } 
                // Correct user.
                else {
                    window.location = "#/principal.html"; 
                }

            }, function() {
                $rootScope.error = "Error en el logueo del usuario";
            });
        }
    }]);

service.js

'use strict';

angular.module('myapp.services', [])
.factory('loginService', ['$http', '$localStorage', 'tokenStorage',
        function ($http, $localStorage, tokenStorage) {
        // THIS IS WORKING PERFECTLY FINE
        return {
            signin: function(data, success, error) {

                $http.post(
                        'http://myweb.com/api' + '/login', 
                        data
                    ).success( function (result, status, headers) {
                        console.log("logged in");

                    }).error(function (data, status, headers, config) {
                        console.log("error. " + data);
                    })
            }
        };

    }]);

Answer №1

Make sure to properly invoke the success function provided by the signin function:

signin: function(data, onSuccess, onError) {

            $http.post(
                    'http://myweb.com/api' + '/login', 
                    data
                ).success( function (result, status, headers) {
                    onSuccess(result);
                    console.log("User logged in successfully");
                    tokenStorage.store(headers('X-AUTH-TOKEN'));

                }).error(function (data, status, headers, config) {
                    console.log("Error occurred: " + data);
                })
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the Row's Background Color in Angular When the Button is Clicked

My code includes a list where each row has a button to open a sidebar. Due to the large number of elements in the list, I want the background color of the row to turn yellow when the button is clicked, as a way to indicate what has been selected. Currently ...

What is the best way to record and share a video with jquery and laravel?

Is there a way to grant users access to record videos within an application and then upload them after previewing? I've been able to successfully record and download a video, but now I'm unsure of how to proceed with uploading it to the server. ...

Looking to retrieve the coordinates of an element following a CSS3 translation using JavaScript?

I came across this issue in two different variations on stackoverflow, but unfortunately the proposed solutions didn't work for me. My problem is that I need to translate an item, but when I try to retrieve its position with obj.style.left or obj.off ...

Set up Node.js application to allow CORS for designated endpoint(s) exclusively

I am currently facing a dilemma with my Node application and how to handle cross-origin resource sharing. In the past, I have used a PHP proxy to bypass this issue when calling endpoints from JavaScript/AJAX. However, I am now looking to streamline the pro ...

The sample Ajax XML code provided by W3Schools is ineffective

While studying xml parsing in ajax on w3schools.com, I came across an example that functioned perfectly online. However, when I saved it to my desktop as abc.html and note.xml, the XML values weren't displaying. Even though the HTML elements were vis ...

Large size causing alignment issues with Bootstrap Tooltip位置混乱

I've encountered an issue with the bootstrap tooltip while using fullcalendar.js. The problem isn't with the fullcalendar library itself, as I included it just to provide context. You can view the problem on this JSfiddle link. The tooltip keeps ...

The functionality of Node async/await appears to be malfunctioning

In an effort to streamline my code and reduce the number of callbacks, I decided to explore using async/await. However, I encountered a problem where Express renders the view before the query is complete. The query results are correct, but they come after ...

AWS Cognito - ECS Task Fails to Start

I'm facing an issue with using JavaScript to execute a task in ECS Fargate. AWS suggested utilizing Cognito Identity Credentials for this task. However, when I provide the IdentityPoolId as shown below: const aws = require("aws-sdk"); aws.co ...

Using ng-repeat with multiple filters in Angular

In this section, I am utilizing ng-repeat to iterate through a list: <tr ng-repeat="d in TranHistory"> <td>{{d.Quantity}}</td> <td>{{d.Qty_Lock}}</td> <td>{{d.Balancedcommodity |filter:GetBalance( ...

Unable to transfer content to clipboard from a Popper element nested within a Dialogue component in Material-UI

If you want to see the bug, try opening this link in Firefox. It almost crashed Chrome :P https://codesandbox.io/s/73z5293391 Click on the OPEN SIMPLE DIALOGUE button. A dialogue will appear, then click on the TOGGLE POPPER button. Now a Popper will be d ...

Validating Angular UI Route state with Protractor

I've been experimenting with the protractor framework to conduct tests on my angular application. Is it possible for me to verify the angular state during an end-to-end test? ...

Tips for Combining Multiple Custom Filters in AngularJS

Is there a way to use AngularJS to chain multiple filters together? I have 3 dropdown menus that I want to use as filters to refine the data in a table. I created a Plunk to showcase what I'm trying to achieve, you can view it at this link The filter ...

organizing various kinds of data values within an array

Within this array, I have two types of variables - an integer and a string. My goal is to sort the array either alphabetically or by the length of the string. However, it seems that the sorting algorithm is prioritizing the integer over the string. ...

The query for Node.js using mysql is not defined

Recently, I've been working with Node.js and attempting to incorporate mysql in conjunction with nodejs. Specifically, I have written a query trying to retrieve numbers from a table: select numbers from TABLE, but the end result shows up as: "undef ...

Finding the nearest ancestor with a specific class using JavaScript

Is it possible to find the closest ancestor by class using a partial class name? For example: <div class="parent-1"> <div class="child"></div> </div> I'd like to achieve something like this: document.get ...

json How to retrieve the first index value in jQuery

As part of my Ajax loop, I am successfully generating JSON and iterating through the results. My goal is to extract only the first index value of JSON which is name. In jQuery, I have the following code: PHP $jsonRows[] = array( "name" => ...

What is the best way to add data from an array to a DOM element in the same order it was retrieved from Firebase?

Utilizing Google Firebase Firestore for data storage and the Open Movie Database (OMD) in combination with Axios to retrieve movie information. I am currently developing a website that allows users to add movies to collections. On the collections page, al ...

Is there a way to retrieve the intersection point (Vector3) of the intersectObjects?

I need assistance in finding the point where a ray cast from 'child' intersects with a mesh (child2) using Raycaster: var raycaster = new THREE.Raycaster(); var meshList = []; meshList.push(child2); for (var i = 0; i < child.geometry.vertices ...

Give a radio button some class

<input id="radio1" type="radio" name="rgroup" value="1" > <label for="radio1"><span><span></span></span>1</label> <input id="radio2" type="radio" name="rgroup" value="2" > <label for="radio2"><span ...

Exploring the World of Websockets with SailsJS and Socket IO, A Journey into the World of Persistent Connections

My current project involves using SailsJS for an application, which has been running smoothly until recently. For the past few hours, I've encountered an issue where I'm not receiving any responses from socket.get(). To investigate, I checked the ...