It appears that the $http request is causing an endless $digest Loop

Looking to determine a user's status in my AngularJS app in order to display specific functionality content, here is the HTML code in my view:

<span ng-show="authService.isSuperUser()">You are a Super User</span>

To check if the user has "superuser" status and show the span, I wrote the following JavaScript code within my service:

this.isSuperUser = function () {

    if (loggedInUser !== null) { // loggedInUser is true in most cases
        return getSuperUser();
    } else {
        return false;
    }

};

var getSuperUser = function(){
    return $http({method: 'GET', url: '/url/to/rest/service/for/superuser' }).then(function (response) {
        return response; // this returns true or false

    }, function () {
        console.log('Yikes! An Error!');
        return false;
    });
};

The getSuperUser function gives the correct result (either true or false), but when testing it in the browser, I encounter numerous Infinite $digest Loop errors. It seems like there's a better approach for implementation to avoid these errors. The HTML view loads when a user visits a specific URL such as myapp.com/#/youraccount, and the

ng-show="authService.isSuperUser()"
is not loaded prior in the app.

Answer №1

Check out this code snippet:

.factory('authService', function($http) {
    return {
         isSuperUser: function () {
             return $http.get(......);
         }
    };

})

.controller('MyCtrl', function($scope, authService) {
    $scope.isSuperUser = authService.isSuperUser();
})

<span ng-show="isSuperUser">you are a super user</span>

When the controller executes, it triggers the service to make an asynchronous call and immediately returns a promise.

This promise is then assigned to a $scope variable named isSuperUser.

The view is bound to this promise. Once it resolves, it will either be true or false, causing ng-show to display accordingly. Until then, it is considered false (at least I think so :P)

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

Sometimes the Navbar options fail to show up consistently on the Navbar bar

I recently launched my website at campusconnect.cc Unfortunately, I've noticed that when resizing the window, the navbar options are shifting up and down. Can anyone help me identify the issue and provide guidance on how to resolve it? ...

AngularJS: Exploring the Purpose of the '?=' Symbol in Angular Directive Scopes

Recently, I noticed some developers using '=?' within the angular scope of a directive. Could someone kindly elaborate on its purpose and how it is used? ...

The Angular $http is triggering an endless loop, resulting in the error message: "Error: 10 $digest() iterations reached and now aborting

I am facing a challenge with Angular $http promise. It appears that the $http promise is causing an infinite loop with the error message "error : 10 $digest() iterations reached. Aborting!" I would appreciate any advice on how to resolve this issue. Just ...

Why is my console showing a SyntaxError with JSON.parse and an unexpected character?

I am facing an issue. When I attempt to call a PHP page for some data with specific requested parameters using AJAX asynchronous call, I encounter the following error: SyntaxError: JSON.parse: unexpected character var jsonData = $.ajax({ u ...

Is there a way to prevent my jQuery from triggering the <a href> unless the ajax post is successful?

I am attempting to update the database and redirect the user's browser to a new page with just one click. Here is how the HTML appears: <a id='updateLiveProgress' style='width:118px;' href='~link~'>Click here</ ...

An easy way to attach a Contextmenu to a specific element

I have implemented a scrolling feature for one of the div elements in my Application. Inside this div, there is a templated table with over 100 rows. Users are able to add or delete rows using a contextMenu. The contextMenu offers 4 options - AddTop, AddB ...

Encountering a "self is not defined" error while utilizing the Jodti-React text editor within a Next.js project

Issue with 'self is not defined' error while using jodti-react in a Next.js project import React, { useState, useRef, useMemo } from "react"; import Dashborad from "./Dashborad"; import JoditEditor from "jodit-react" ...

Is there a way to automatically activate the "Add" button when I hit the enter key in the text box?

Being someone who relies on to-do lists, I implemented a system where you can input tasks into a textbox and click the add button to see them listed below. However, I found it cumbersome to keep clicking the add button every time I wanted to quickly add mu ...

Guide on utilizing AngularJS Filter service without HTML for Chrome extension development

Currently, I am attempting to utilize the filter service in AngularJS within my Chrome extension. However, I am unsure of how to properly obtain and inject it into my function. At this time, my code looks like: chrome.contextMenus.onClicked.addListener(fu ...

JavaScript library unsuccessful in transferring data to PHP script

I am facing an issue while trying to transfer variables from javascript to a php file for execution. The problem is that the php file is not being called or executed, even though I have confirmed that it works properly when tested individually. $(function ...

Conceal the child elements underneath a selected element using jQuery

I am currently working on an order form within a website and the HTML code is structured as below: <table class="variations"> <div class="tawcvs-swatches" data-attribute_name="attribute_pa_t-shirt- one-color"> <span class="swat ...

The functionality of Nodejs exec is malfunctioning

I need assistance with executing DOS commands using the exec function: java -jar D:\selenium\selenium-server-standalone-2.40.0.jar -htmlSuite "*firefox3 C:\Users\AppData\Local\Mozilla Firefox\firefox.exe" "http://google. ...

Issues encountered with sending post requests to a yii2 application when using Angular4

After implementing the following code: this.http.post('http://l.example/angular/create/', {name: 'test'}).subscribe( (response) => console.log(response), (error) => console.log(error) ); I encountered an error on ...

Sending Email Form in PHP using JQuery and Ajax for seamless user experience

Looking to create an email form in HTML with PHP, but running into the issue of the page reloading after submitting? Many people turn to jQuery and AJAX to solve this problem. While you may have come across solutions on Stack Overflow, as a non-native Engl ...

Issues with importing files have been reported on Node.js version 11.8.0

I'm currently working on a program that utilizes a large object filled with dictionary words. I've decided to import this object from a separate file due to its size, but I encountered an error stating that Node.js doesn't recognize the obje ...

Display the length of an array using AngularJS

Hey there, I'm currently having an issue with printing a list where each entry is supposed to follow the format "element X of TOTAL". However, instead of displaying the total value, it appears as blank text. It seems like a simple mistake, but for som ...

Interacting with Node JS by submitting a request and obtaining a response

Hey there, I'm just starting out with Node JS and trying to grasp how client-server communication works. Here is the file on the server (express.js): app.post('/action', (req, res) => { const status = action.doAction(req); }); ...

What is the optimal value for the variable x in this scenario?

What is the correct value for X to make this condition valid? // Your code goes here if (x == 1 && x === 2) { console.log('Success!'); } ...

I'm baffled on how to find access to ParametricGeometry within Three.js

I've been looking into how to access ParametricGeometry because I keep encountering this message when I attempt to use it: "THREE.ParametricGeometry has been relocated to /examples/jsm/geometries/ParametricGeometry.js" Any ideas on how to do this wou ...

Unable to successfully remove item by ID from mongoDB within a Next.js application

Currently, I am developing an application using NextJS for practice purposes. I'm facing challenges in deleting single data from the database with the findByIdAndDelete function. Error encountered: CastError: Cast to ObjectId failed for value "undef ...