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

Checking variable length time with JavaScript Regular Expression

My specific requirement is to validate a string ranging from 1 to 4 characters in length (where H stands for hour and M represents minutes): If the string has 1 character, it should be in the format of H (a digit between 0-9). A 2-character string should ...

Is window.open exclusive to Firefox?

Apologies if this question has been asked before! I am experiencing some issues with my Javascript code. It works perfectly in Firefox and opens a pop-up window as expected. However, in IE 9 it does nothing, and in Chrome it behaves like a link and change ...

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

Is it possible to store Socket.IO responses in a cache for quicker retrieval?

Consider this scenario where I have a websocket implementation shown below: let itemsArray = []; function fetchData() { itemsArray = await db.query(`SELECT * FROM Items`); } function emitData() { io.sockets.in("room_foo").emit("data", JSON.stringify ...

Creating dynamic grids in React.js by utilizing HTML

Currently, I am tackling one of the projects on FCC which is the Game of Life. Prior to diving in, my focus is on figuring out how to render a grid on the page. I aim to modify the table dimensions while ensuring it fits neatly within its container. The ...

Is there a way to filter and tally the JSON objects that have latitude and longitude within a 10km radius from the

I'm currently working on filtering and counting objects from an API endpoint that fall within a 10km radius of the specified origin. My main challenge lies in correctly filtering the API results and tallying the number of matching items. While I succ ...

Registering a function for chart.js plugins that manipulates external data

Is there a way to pass external data to the chart.plugins.register function? I'm struggling because I can't access the necessary context: Chart.plugins.register( { beforeDraw: function (chart) { //implementation } }); I attempted using ...

Ways to import a library in JavaScript/TypeScript on a web browser?

I'm currently working on a project that involves a TypeScript file and an HTML page. Right now, I am loading the necessary libraries for the TypeScript file in the HTML Page using script tags like <script src="https://unpkg.com/<a href="/cd ...

Get Subject Alternative Name from X.509 in a Node.js environment

Having trouble retrieving the SAN from a DoD Smart Card, as the subject alternative name is returning othername:<unsupported>. I have not been able to find many examples on how to parse this information. I would have thought that X509 li in node woul ...

"What is the process for developing a Web-component with Vue and typescript that can be used in

Utilizing vue-custom-element, I have successfully created a Web component in Vue and integrated it into Angular. This setup operates seamlessly for Vue+js: import Vue from 'vue' import Calculator from './components/Calculator.vue' impo ...

Storing JSON strings in PHP differs from storing them in JavaScript

Using JavaScript, I can save a cookie using JSON.stringify(), which saves the cookie directly like this: '[{"n":"50fb0d0cc1277d182f000002","q":2},{"n":"50fb0d09c1277d182f000001","q":1},{"n":"50fb0d06c1277d182f000000","q":1}] Now, I am sending this t ...

What is the functionality of an Angular service that retrieves an

It appears that Angularjs services are constructed by passing in a Contructor function: app.service('serviceName', function(){ this.var1 = 'foo'; this.method1 = function(){ } }); Angular executes this function using the new ...

Troubleshooting AngularJS: Diagnosing Issues with My Watch Functionality

I need to set up a watch on a variable in order to trigger a rest service call whenever its value changes and update the count. Below is the code snippet I have: function myController($scope, $http) { $scope.abc = abcValueFromOutsideOfMyController; ...

Storing the background color in a JavaScript variable

I've been experimenting with creating a fade in and out effect for a background image on a website. I've also been attempting to capture the background color of a div and store it in a variable. Here's what I have tried: elem = document.ge ...

Steps to create a new window using Raphael JS

Is there a way to create a new window in Raphael similar to using "_blank"? ...

Perform the function prior to making any adjustments to the viewmodel attributes

Within my view, I am showcasing employee details with a checkbox labeled Receive Daily Email. When a user interacts with this checkbox, I want to trigger an AJAX function to validate whether the user is allowed to modify this setting: If the result is tru ...

Click to add a card

Attempting to incorporate a new row with the click of a button dynamically has proven to be challenging for me. As someone who is relatively new to JavaScript, I am struggling to figure it out. In the demonstration provided below, you will notice that noth ...

Please indicate the maximum number of digits allowed after the decimal point in the input

My input form uses a comma as the decimal separator: HTML: <form id="myform"> <label for="field">Required, decimal number:</label> <input class="left" id="field" name="field"> <br/> <input type="submit" va ...

Using React to update an existing array of objects with a new array containing objects of the same type

My issue involves an array in a class's state, referred to as A. A is populated with objects of type B through the function f in the constructor. Subsequently, I create a new array of objects of type B called C using f and new data. Upon setting the s ...

Utilizing PHP Variables in an External JavaScript: A Step-by-Step Guide

I am attempting to utilize an array generated in PHP within my external JavaScript. My PHP code retrieves images from a directory based on the user ID provided via URL and stores them in an array. I aim to use this array in JavaScript to create a photo sli ...