No results in AngularJS

I have two factory functions:

Factories

factory.getCurrEmployee = function()
{
    data = {"api_token": authenticationFactory.getToken()};
    url = GLOBALS.url + 'show/employee/' + $cookieStore.get('employeeid');
    return requestFactory.post(url, data)
        .then(function (response) {
            return response.data.result.Employee;
        }, function () {
            $window.location.assign('/');
        });
}

factory.isSuperadministrator = function() {
    factory.getCurrEmployee().then(function (employee) {
        if(employee.Role == 'Superadministrator')
        {
            return true; //console.log('Superadministrator')    <- that console.log is visible in my console
        }
        return false;
    });
}
return factory;

In the controller, I expect to receive either true or false (indicating whether a user is a Superadministrator or not), but the result is blank. When I console.log in my factory.isSuperadministrator, the result is true.

Controller

console.log(employeeFactory.isSuperadministrator());

Why is this not functioning as expected?

Answer №1

The promise was not properly returned from the factory.getCurrEmployee function inside the factory.isSuperadministrator function. I also conducted a minor refactoring to enhance the efficiency of your code.

factory.isSuperadministrator = function() {
    return factory.getCurrEmployee().then(function (employee) {
        return employee.Role == 'Superadministrator';
    });
}

However, the above modification does not completely resolve your issue; it simply displays the promise object in the console using the print function. To fully address the problem, you must utilize the .then method with a callback on the promise returned by

employeeFactory.isSuperadministrator()
as demonstrated below:

Controller

employeeFactory.isSuperadministrator().then(function(data){
   console.log(res);
});

Please adhere to the same instructions provided in this answer

Answer №2

Experiment

checkIfEmployeeIsSuperadmin().then(function(result){
displayResult(result);
});

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

What is the best way to calculate the sum of table data with a specific class using jQuery?

If I had a table like this: <table class="table questions"> <tr> <td class="someClass">Some data</td> <td class="someOtherclass">Some data</td> </tr> <tr> <td class="s ...

Refreshing CSS-Element-Queries following an ajax request

I’ve been utilizing css-element-queries from the https://github.com/marcj/css-element-queries repository to tailor styles based on an element's dimensions. However, I encountered an issue when dynamically adding elements via ajax calls. The new elem ...

What steps should I take to set up a personalized prompt for user input in AngularJS?

After setting up the UI and scope variables, I am faced with a task that requires the function to only continue when either the left or right button is clicked (meaning $scope.isLeft or $scope.isRight will be true). This behavior is akin to how a regular J ...

What is the best way to display JSON response as code instead of a string in AngularJS?

When retrieving my article from the database as a JSON object, I encounter an issue with the body content. The HTML codes in the body are displayed as strings within double quotation marks by AngularJS. How can I resolve this? Angular controller snippet: ...

What is the best way to showcase one object per day when I have an array of 30 objects in Ionic 4?

I'm looking to showcase a different quote in my app every day for 30 days using an array of 30 quotes. How can I achieve this daily quote rotation in Ionic 4? ...

Using Angular template to embed Animate CC Canvas Export

Looking to incorporate a small animation created in animate cc into an angular template on a canvas as shown below: <div id="animation_container" style="background-color:rgba(255, 255, 255, 1.00); width:1014px; height:650px"> <canvas id="canv ...

What is the process for generating an array of arrays in a React component?

I'm currently working on developing a word-guessing game similar to Wordle using React. The interesting twist in this game is that players have the ability to choose both the number of attempts allowed and the length of the word they are trying to gue ...

Encountering MIME type error (text/html) during Angular project deployment

I am facing an issue while trying to deploy a project built with Angular/CLI 6.12.0. After transferring the content of the "dist" folder to a server, I encountered a console error related to MIME type. The module at address "http://www.sylvainallain.fr/p ...

Tips for determining the presence of a query string value using JavaScript

Is there a way to detect the presence of q= in the query string using either JavaScript or jQuery? ...

Is it possible to utilize the same Context in multiple forms within React?

Is it possible to utilize React Context to store the state of multiple forms, or should each form have its own unique Context? Below is a snippet of code that showcases the use of React Hooks API: In FormContext.js ... import {FormReducer} from './ ...

Encountering the error "Vue 2.0 encounters an undefined push during router.push

I'm currently working on a project that involves implementing a function to route the list of subMenus displayed by the mainMenu. Each subMenu is identified by its specific name, which I would like to append and use as the route path that I am aiming ...

The 'in' operand is invalid

I am encountering a JavaScript error: "[object Object]" TypeError: invalid 'in' operand a whenever I attempt to perform an AJAX request using the following code: .data("ui-autocomplete")._renderItem = function( ul, item ) { return $( " ...

What is the method for viewing a PDF file on ng-click without automatically downloading it in AngularJS?

When the user clicks on the link that says "Click to get your file", I am able to download the file. However, now I want to open the PDF file in a modal window and prevent the user from downloading it. This is My Controller: var resumeJson = { "j ...

Using Ajax and PHP to store multiple checkbox selections into the database

I currently have 32 checkboxes on my page that I need to track the checked status for. In my JavaScript, I am looping through each checkbox and assigning a value of '1' for checked and '0' for unchecked. // Example for one checkbox if ...

The process of organizing and arranging the content that appears on a webpage is in

Seeking a solution to achieve a similar effect like this example. Wanting the sections to transition nicely when clicked on. Should I use a Jquery plugin or implement it with CSS? ...

JSON.stringify not behaving as anticipated

I am working on the code below; var data = []; data['id'] = 105; data['authenticated'] = true; console.log(data); var jsonData = JSON.stringify(data); console.log(jsonData); The initial console.log is displaying; [id: 105, authenti ...

Setting up a Vue 3 parent component to emit events to a child component: a step-by-step guide

Seeking assistance with setting up a Vue 3 Tailwind parent component button to trigger a HeadlessUI transition event in a child component. The objective is for the button in the parent to emit an event, which the child will then watch for before triggering ...

The function crypto.randomUUID() does not exist in the Vitest library

vite.config.ts import { sveltekit } from '@sveltejs/kit/vite'; const config = { plugins: [sveltekit()], test: { include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], environment: 'jsdom', glo ...

Error encountered: Index 109 - The function $.ajax(...).success is not recognized as a valid function while working with jQuery in a Node

I'm just starting to learn about jquery and have been experimenting with ajax in my recent code. Below is the snippet of what I have implemented: $(function(){ $("#status").change(function(){ if($(this).is(':checked')) ...

Integrating information from an API into the Document Object Model

const url = `https://catfact.ninja/fact?max_length=140`; const getFact = () => { return fetch('https://catfact.ninja/fact?max_length=140') .then(res => res.json()) } const createFactDiv = (fact) => { const factContainer = documen ...