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

Struggling with effectively executing chained and inner promises

It seems like my promises are not completing as expected due to incorrect handling. When using Promise.all(), the final result displayed with console.log(payload) is {}. Ideally, it should show something similar to this: { project1: { description: & ...

I wonder where the file from the HTML form download has originated

Recently, I've been experimenting with the developer tools in Chrome to observe the behavior of websites at different moments. It has proven useful in automating certain tasks that I regularly perform. Currently, my focus is on automating the process ...

What is causing the error when trying to parse a JSON with multiple properties?

Snippet: let data = JSON.parse('{"name":"dibya","company":"wipro"}'); Error Message : An error occurred while trying to parse the JSON data. The console displays "Uncaught SyntaxError: Unexpected end of JSON input" at line 1, character 6. ...

Tips on sending asynchronous requests to a PHP page using jQuery AJAX

As a newcomer to web development, I am working on creating a social networking website for a college project. One feature I want to implement is updating the message count in the menu every time there is a new message in the database for the user (similar ...

Incorporating ngRoute for routing with an Express backend

After reading multiple answers regarding this topic, I am still struggling to grasp the concept. Currently, I have an angular front-end and I am attempting to utilize $routeProvider to load partials for my single page application. However, I keep encounter ...

Every time the page is refreshed, ExpressJS and NodeJS are working together to duplicate the array

var express = require("express"); var router = express.Router(); const fs = require("fs"); const path = require("path"); const readline = require('readline'); const directoryPath = path.resolve(__dirname,"../log ...

I am encountering challenges with React.js implemented in Typescript

Currently, I'm grappling with a challenge while establishing a design system in ReactJS utilizing TypeScript. The issue at hand pertains to correctly passing and returning types for my components. To address this, here are the steps I've taken so ...

Navigating the issue of updateMany not functioning properly in mongoose and nodejs

I need assistance with updating the author name of a post whenever the user updates their profile name. My code is as follows: router('/:id', async (req, res) { if (req.body._id == req.params.id) { try { const user = await ...

What are the steps to incorporating an Image in a React Native application?

My Image is not showing up when I try to render it using image uri, and I'm not sure why. Here is the code snippet I'm using in a React Native project. import React from 'react'; import styled from 'styled-components/native'; ...

Disable the button until all input fields contain text in ASP

Curious if anyone knows how to disable a button until all text boxes have input in ASP.NET and C#. Here is an image showing the scenario I'm referring to - wanting to gray out the commit button. Thanks, Chris! ...

Directing JSON POST Request Data to View/Controller in a Node.js Application

Currently, I am working on a project hosted on a local server at http://localhost:3000/. This server receives a post request from another server in the following manner: return requestLib.post({ url: 'http://localhost:3000/test', timeout ...

How to verify the parent nodes in a jstree

I have implemented a two state jstree. However, I am encountering an issue where it is not possible to select any other node in relation to a node. My goal is that when I click on a specific node, all of its parent nodes should also be checked. Any assist ...

"Want to learn how to dynamically disable an input field in AngularJS when another field is selected? Find out how to achieve this using the

Hey there, I'm dealing with two input fields. Input field A is a drop-down menu and input field B. They both have the same value (same ng-model). My goal is to clear the second input field whenever the user selects an option from the dropdown. Can any ...

The issue causing "ReferenceError: fetch is not defined" is causing the test to fail

There seems to be an issue with my project where 'node-fetch' is installed, but the rest of the files are not importing it and the tests are not failing import { IQuery } from 'models/IQuery.interface'; import { NextApiRequest, NextApiR ...

Guidelines for cycling through a series of HTTP requests and effectively saving the data from each cycle into an array

Utilizing Spotify's API search feature, I am working with an array of SongSearchParams that consist of title and artist parameters: export class SongSearchParams { public title: string; public artist: string; constructor(title: string, a ...

Having problems with Javascript and CSS not playing well together?

I have implemented a button from this source, but it does not appear correctly on my page. You can view the screenshot here. It seems like there is a conflict between the saved changes and the CSS. How can I resolve this issue? In addition, I am facing ...

What is the best way to integrate JQuery URL in Joomla components?

Can anyone show me how to load a jquery URL in Joomla (Component)? I have a button that, when clicked, will reload the page and use the GET method to display a value from a variable. JavaScript: jQuery("#btnclickme").click(function(){ jQuery("#divpro").l ...

Child object referencing in JavaScript

As I delved into testing Javascript, a curiosity arose regarding the interaction between child and parent objects. Would the parent object dynamically update to reflect changes in the child object's value, or would it remain static at the initial stat ...

The content of xmlhttp.responseText is not being displayed in the innerHTML

As part of my ongoing effort to enhance my understanding of Ajax for work purposes, I have been following the W3Schools tutorial and experimenting with my Apache2 server. In this process, I have placed a file named ajax_info.txt on the server (in /var/www ...

What is the process for verifying a checkbox after it has been selected?

I simplified my code to make it easier to understand const [factor, setfactor] = useState(1); const [nullify, setNullify] = useState(1); const Price = 10; const Bonus = 15; const finalPrice = (Price * factor - Bonus) * nullify; // start ...