0

In the rootScope of my project i have defined a function that realizes an $http call.

angular.module('rsa',['ngRoute', 'ngCookies', 'ngMaterial'])
.config(function($routeProvider, $httpProvider){
    $routeProvider.when('/chapters', {
        ...
    });

    $routeProvider.when('/themes', {
       ...
    });

    // ... more routes

    $routeProvider.otherwise('/home');
  })
.controller(...)
.run(['$rootScope', 'UserService', '$location', '$cookies','$http', '$q', 
  function(rootScope, UserService, location, cookies, http, $q){
      rootScope.isAdmin = function(){
      return $http.get('/isAdmin').then(function(resp){...}, function(resp)
      {...})
   }
}])

rootScope's isAdmin method causes an infinite digest loop error. Meanwhile, the same $http call (from isAdmin methods) works well inside other controllers.

I've read a little about what can be the problem and i found out that the $http service calls the $apply to force the $digest cycle but i don't understand what happens exactly with the $http service that drove me to get the following result in the console.

console

This is th html snippet:

<a class = "navbar-brand" href="#/admin" ng-if="isAdmin()"> Administration </a>

Q1: Why is $http.get() causing an infinite number of $digest cycles.

Q2: Why does it only happen on rootScope and not in any other scope.

BTW xhr syncronous work fine and i am using angular 1.6.4

  • the run module in angular dont support promises check this out https://stackoverflow.com/a/28609571/8303694 – Jesus Carrasco Aug 25 '17 at 16:53
  • FYI, `isAdmin()` returns a promise, not the result (which, being an object, will always evaluate as true in `ngIf`). Also, it's usually best not to use a function call as expressions in the view; they do have a tendency to start infinite digest loops. – Harris Aug 25 '17 at 16:54
  • @JesusCarrasco That's an interesting point, though in this case it's simply defining a function that uses promises; it doesn't itself attempt to use them. – Harris Aug 25 '17 at 16:57
  • im guess you want to know if a user is has some privilegies, suppose you must have a service when loggin. and save it maybe localsession, and then inject thos service in the run time, and asking if has privilegies. – Jesus Carrasco Aug 25 '17 at 17:02
  • @harris i am aware of that. Main problem is that the use of the promise causes inf digest loop. – Youssef Ilyès Aug 25 '17 at 17:59
  • Why not resolve that first, store it, and then reference the stored value? You won't run into this issue, and you won't be making an HTTP call _every digest cycle_. – Harris Aug 25 '17 at 18:00
  • I am not really looking for solutions. I want to know what happened there. What made the digest cycle execute infinitely. – Youssef Ilyès Aug 25 '17 at 18:05

0 Answers0