AngularJS directive facing a callback problem

Having trouble with callbacks while calling a service function

This is the function defined in registrationService

function checkUserAccess(incentiveLevel, callback, displayRegistrationView) {

            var url = "...";
            httpWrapperService.get(url)
                .then(
                function done(data) {
                    var hasPermission = incentiveLevel <= data.Level;
                    callback(hasPermission);
                    if (displayRegistrationView && hasPermission == false) {
                        showRegistrationViewForLevel(incentiveLevel);
                    }
                },
                function error(errorObject) {

                    alert("User does not have access\r\nTODO : show popup for registration/login");
                }

            );
            return false;
        }

In my directive, I use this function as:

function authenticate() {
                registrationService.checkUserAccess(2, function (hasPermission) {
                    if (hasPermission == false){
                        return false;
                    }
                    else{
                        return true;
                    }
                });
            }




function retrieveDocs() {
                var target = authenticate()
                if(target)
                {
                  //load both private and public
                }
                else
                {
                  // load only public
                }

            }

The issue at hand is with another function retrieveDocuments, when the user is logged in it should enter into the if(target) block. However, during debugging, it indicates that target is undefined, resulting in the control flowing to the else part, incorrectly. It seems like there's a callback problem but unsure how to resolve it.

Your assistance would be greatly appreciated. Thanks

Answer №1

To handle the asynchronous nature of hasUserAccessToLevel(), utilize the $q service in your code. The reason why checkAuthentication() returns undefined is because hasUserAccessToLevel() does not return a value at the time of call. The solution is to return a promise object instead.

You can structure your code like this:

function checkAuthentication() {
    var defer = $q.defer();
    registrationService.hasUserAccessToLevel(2, function (hasAccess) {
        defer.resolve(hasAccess);
    }, function () {
        defer.reject();
    });
    return defer.promise;
}

function loadDocuments() {
    checkAuthentication().then(function (target) {
        if (target) {
            // Load both private and public documents
        }
        else {
           // Load only public documents
        }
    });
}

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

Having trouble transferring data from JavaScript to PHP via POST method

Hi there, this is my first time posting and I could really use some assistance. I have a bit of a roadblock with two Symfony forms on a page that don't seem to be working properly. The first form is for a contract, while the second one is used to pop ...

What is the method for displaying a canvas scene within a designated div element?

I need help displaying a scene inside an existing div on my webpage. Whenever I try to do this, the canvas is always added at the top of the page. I attempted to use getElementById but unfortunately, it didn't work as expected. What could I be overlo ...

How can a parameter be added to a query string only when there is a value present in a textbox using JavaScript?

Hello everyone, I am looking to add parameters to a URL only if the search text box value is different from the default. I have three search text boxes and I want to include them in the URL. Below is my code snippet: $("#search-btn").click(function (e) { ...

Click the mouse to create a unique path from the list items within the <ul> <li> using jQuery

My current listing contains various files and folders: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fon ...

The database threw an error: "Duplicate key found in collection causing MongoError: E11000"

I'm currently in the process of updating an object within an array found in a document "state": [], "users": [{ "ready": false, "_id": { "$oid": "5fb810c63af8b3 ...

Execute Cheerio selector once the page has finished loading

Hey there! I'm trying to extract the URL value of an iframe on this website: I've checked the view page source but couldn't find the iframe. Looks like it's loaded after the page is fully loaded through JavaScript. Could it be that ...

Vue-Firebase: A guide to linking multiple Firebase services in a single app

I am facing an issue with connecting to two firebases within the same project. In my project, I have two javascript files that connect to each firebase separately, which seems fine. Here is how I import them: import db from '../FireBase' i ...

adjust back side height of flip box does not function on IE web browser

I'm currently working on flipping a div/box, and while it's functioning correctly, I'm facing an issue with the height of the back side exceeding that of the front side. This causes the flipped div to always push down to the next element (e. ...

The PHP AJAX call is returning an undefined response status

I'm facing two issues here. The first problem is that when I try to access response.status, it returns undefined. The second issue is related to the creation of "$_SESSION['promo-code'] = $arr". When I enter a promo code, I encounter the fol ...

Converting Ajax to JSON with Jquery offline and Manifest for enhanced offline web applications

Looking to create an offline web application, I'm in the process of transitioning from Ajax to JSON using JQuery offline. Here is the initial Ajax code: $.ajax({ url: contentpage, data: contentpagedata, cache: false }).done(function( html ) { ...

NodeJS controller function to generate and send a response

I'm facing an issue with my controller method where I am unable to send a response to the user, even though the value is displaying in the console. Below is my code snippet: const hubHome = (req,res) => { const hubId = req.params.hubId; fetch ...

switch out javaScript for selenium

I'm attempting to replace the JavaScript functionality of a web page using Selenium (in Java with Firefox Geckodriver, if that makes a difference). Consider this webpage: <HTML><HEAD></HEAD> <BODY> <DIV id="time">Ti ...

Unexpected issue encountered when working with JSON in Node.js

I've searched through countless solutions on stackoverflow, but none of them seem to work for me. It's really frustrating not understanding what's going wrong. Below is the code I'm having trouble with: var data = ""; req.on('dat ...

Re-establishing connections in the force-directed graph model

Just getting started with d3.js and I'm currently attempting to reconnect paths between nodes on a force graph. Here is an example image of what I am trying to achieve: I want to be able to drag the red circle and have the path connected to other nod ...

Determine the number of elements chosen within a complex JSON structure

I need to figure out how to count the length of a jsonArray, but I'm stuck. Here's an example to start with: https://jsfiddle.net/vuqcopm7/13/ In summary, if you click on an item in the list, such as "asd1", it will create an input text every t ...

Modifying data on the fly in Angular

I attempted to dynamically modify my data without continuously requesting it from the server. Below is the code snippet I am currently using: $scope.total_earned = () => { //ng-click function from frontend splice(); loadChartData(1); } ...

Steps for changing text box border to red upon validation failure

I am struggling to change the textbox border color to red when validation fails in my AngularJS application. I would appreciate any guidance on how to achieve this. Thank you. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

Optimizing the particle rendering speed for HTML5 <canvas> elements

Currently conducting an experiment to enhance the maximum particle count before frame-rates begin to decrease in HTML5 Canvas. Utilizing requestAnimationFrame and employing drawImage from a canvas as it appears to be the most efficient method for image re ...

Having trouble with your jQuery AJAX function not receiving the text returned from your PHP file?

After extensive searching, I have come across several individuals facing the same issue as me, but unfortunately, none of them seem to have found a solution. The problem at hand is that PHP is not providing any data to the AJAX function. When I try to dis ...