AngularJs promise is not resolved

Before processing any request, I always verify the user's authorization. Here is the factory code that handles this:

(function()
{
    angular.module('employeeApp').factory('authenticationFactory', authenticationFactory);

    function authenticationFactory($cookieStore,$cookies,requestFactory,$location,GLOBALS,constants,$q)
    {
        var factory = {};

        factory.validateUser = function()
        {
            var vm = this;
            vm.deferred = $q.defer();

            if($location.path() != '/')
            {
                var api_token = factory.getToken();

                factory.isValidToken(api_token).then(function(response) {
                    if (response.status != 200) {
                        $location.path('/');
                    }
                    data = {"api_token": api_token};
                    return requestFactory.post(GLOBALS.url + 'show/employee/' + $cookies.get('employeeid'), data)
                        .then(function (response) {
                            vm.deferred.resolve(response.data);
                            console.log(vm.deferred);
                            return vm.deferred.promise;
                        }, function(response) {
                            vm.deferred.reject(response);
                            return vm.deferred.promise;
                        });
                });
            }
        }
        return factory;
    }
})()

When I output vm.deferred using console.log, it shows as an object.

However, when I call

console.log(authenticationFactory.validateUser());
in my routes file, the console displays empty.

(function () {

angular.module('employeeApp').config(routeModule).run(run);

routeModule.$inject = ['$routeProvider'];

function routeModule($routeProvider)
{
    $routeProvider.when('/', {
        templateUrl: '../views/login.html',
        controller: 'authenticationController',
        controllerAs: 'authenticationCtrl'
    })
    .when('/home', {
        templateUrl: '../views/index.html',
        controller: 'homeController',
        controllerAs: 'homeCtrl',
        resolve: {
            message: function(authenticationFactory){
                return authenticationFactory.validateUser();
            }
        }
    })
    .when('/werknemer/:id', {
        templateUrl: '../views/employee/employee.html',
        controller: 'employeeController',
        controllerAs: 'employeeCtrl'
    })
    .otherwise({
        redirectTo: '/'
    });
}


function run(authenticationFactory)
{
    console.log(authenticationFactory.validateUser());
}
})();

I've been stuck on this for hours now, any help would be greatly appreciated!

Answer №1

It seems like there may be a misunderstanding in your approach to utilizing Angular's $http service. The $http.post method actually returns a promise, which is essentially a placeholder for the eventual resolution of the request. In your current setup, merely calling

authenticationFactory.validateUser()
will return the unresolved promise.

If your authenticationFactory is already set up to return a promise object, you should handle it as follows:

function execute(authenticationFactory) {
    authenticationFactory.validateUser().then(function(response) {
        console.log(response);
    });
}

I recommend referring to the Angular promise service documentation to grasp a better understanding of working with promises effectively.

In addition, it appears that there might be an issue with how you're handling Angular's dependency injection in your second example.

In the second snippet, the authenticationFactory does not seem to be properly injected, leading to an undefined reference.

Remember that during the module's config phase, only providers can be injected, making it impossible to inject the authenticationFactory directly into your config function (unless you create and inject an authenticationFactoryProvider).

You can consider rewriting the code from the second example to resemble this structure. Note the usage of the inline array dependency annotation, which is considered best practice according to the Angular documentation. While using $inject explicitly can work, it's easier to make mistakes and is less clear in terms of what is being injected.

Note: This revised code is untested.

(function () {

var employeeAppModule = angular.module('employeeApp');

employeeAppModule.config([
    '$routeProvider',
    function($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: '../views/login.html',
            controller: 'authenticationController',
            controllerAs: 'authenticationCtrl'
        })
        .when('/home', {
            templateUrl: '../views/index.html',
            controller: 'homeController',
            controllerAs: 'homeCtrl'
        })
        .when('/employee/:id', {
            templateUrl: '../views/employee/employee.html',
            controller: 'employeeController',
            controllerAs: 'employeeCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
    }
]);

employeeAppModule.run([
    'authenticationFactory',
    function(authenticationFactory) {
        console.log(authenticationFactory.validateUser());
    }
]);
})();

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

Utilize JavaScript conditions to dynamically apply styles within your web application

I am facing a challenge with managing two separate <style> tags that each contain a large number of styles and media queries. The issue is that one set of styles is intended for desktop users, while the other is meant for mobile users. When both se ...

A guide on transforming JSON data into HTML using Rails

I'm struggling with parsing JSON on a webpage. My webpage is designed with circles, where clicking on a circle triggers a call to the controller to retrieve specific information from a database and display it as graphs and text. The issue I'm fa ...

Capturing errors during function declaration in JavaScript

A problem has arisen in the below function definition due to a script error function foo () { try { var bar = function() { ERROR } } catch (exception) { console.debug("exception"); } } foo(); However, th ...

Can the caller function's arguments be altered using Function.prototype.apply()?

function modifyValues(a,b){ console.log(arguments); //["oldValue","oldValue"] var newArguments = updateValues.apply(this,arguments); for (var i=0;i<arguments.length;i++){ arguments[i] = newArguments[i]; } console.log(arguments); // ...

What are the distinctions between altering the value of a textarea with JS and user input?

I've come across an interesting scenario that I'm hoping someone with more expertise in JavaScript can help me with. There is a popular online forum site that I frequently use. In the past, I was able to easily update a comment textarea using Jav ...

Tips for adjusting image size to take up only half of the screen in NextJS

Struggling to resize an image to fit only 50% of the screen in NextJS? The Image component provided by NextJS comes with its own inline styling, making it tricky to customize. Currently, I attempt to style the image by wrapping the Image component in a spa ...

Creating dynamic routes in express.js with fixed components

I'm exploring how to create a route in express that captures URLs like this: /events/0.json Here's what I've attempted so far (but it's not working as expected): router.put('/events.json/:id.json', isLogged, events.update) ...

Initially, my PDF file does not get selected, except in the Internet Explorer browser

I am currently facing an issue with selecting PDF files in Internet Explorer. The process works smoothly in Google Chrome, but I encounter a problem when trying to select PDFs in IE. Specifically, when I attempt to select a PDF for the first time in Inter ...

Issue with dropdown list removeClass function

I am encountering an issue with the Jquery dropdown list click function. The addClass method is working properly, but the removeClass method is not functioning as expected. When I click on the dropdown list, it does not hide. Here is a live demo: http://j ...

I have incorporated jquery-1.2.6.js into my project but I am encountering difficulties utilizing the live method

C# foreach (DataRow Row in oDs.Tables[0].Rows) { LitPreferances.Text += "<Li ID=LI_" + Row["pk_Preference_Branch_ID"].ToString() +"_"+ Row["pk_Preference_BranchType_ID"].ToString() +">" + Row["Branch_Name"].ToString() + "&nbsp;&nbsp;< ...

Connecting via web sockets through SSL is not functioning properly

My Web Socket functions correctly in both the localhost and production environments (https://www.example.com). However, upon deploying the same code to the pp environment (), I encounter the error message: WebSocket handshake - Unexpected response code: 4 ...

What is the best way to utilize a For each loop with a controller object?

I am struggling with a problem in my Angular foreach loop where I keep getting an Undefined value when trying to access it. Can someone advise me on how to modify the code below so that I can successfully access the value and store it in $rootScope? patie ...

When selecting the "Open Link in New Tab" option in Chrome, the Angular app's routing will automatically redirect to the login page

I am facing a peculiar issue in my Angular 2 application that I need help troubleshooting. Currently, the routing within my app functions as intended when I click on links to navigate between different components. Here is an example of how the routing path ...

What is the purpose of defining the initialState in Redux?

As per the Redux documentation, it is considered a best practice to establish an initialState for your reducer. However, maintaining this initialState can become challenging when the state relies on data from an API response, leading to discrepancies betwe ...

Prevent selection duplication in adjacent select by disabling the option in AngularJS ng-options

In my table, I have 2 select options that change dynamically. <tr> <th>Start time</th> <th>End time</th> </tr> <tr ng-repeat="s in config.time"> <td> <select ng-model="s.start_time" ...

Ways to time animations differently and activate two animations at the same time in every loop

I have 3 hidden text boxes that I want to fade in and slide down simultaneously by 40px when the DOM loads. They should be staggered so that each one triggers after the previous animation finishes. Below is the relevant JavaScript code snippet: jQuery(fu ...

JWT - Effective strategies for enhancing the user experience for a returning logged-in user

My client authentication system involves storing a JWT in `localStorage` once the user is verified. However, I'm not satisfied with the current user experience when a returning user is redirected straight to a new page without warning. window.locatio ...

React: Updating useState array by removing the first element triggered by an event or timer

I am currently working on a function that populates a useState array containing objects representing cars. These cars appear on the left side of the screen and move across until they are off-screen. My goal is to remove these cars from the state array once ...

Steps for setting up i18nextStart by including the i

I am working on developing a multilingual app using the i18next package. Unfortunately, I am experiencing issues with the functionality of the package. Below is an example of the i18next file I have been using: import i18n from "i18next"; impor ...

Is the Vuex mutation properly formatted?

Is the mutation method correctly written to modify the initial state array? I'm uncertain about the last few lines of the mutation method. What am I missing, if anything? // Storing state: { flights: [ {trip_class: 0, number_of_change="1"}, ...