2

Why am I not able to assign value to $rootScope with the following code.

 fetchIp().then(function(response){
        $rootScope.nodeIp = (response.length == 0 ? "localhost" : response[0]);

    });

var root = 'http://' + $rootScope.nodeIp + ':8080/';

It shows it as 'undefined'

af_khan
  • 1,030
  • 4
  • 25
  • 49
  • You use this code into app.js or controller – Manoj Bhardwaj Mar 13 '18 at 09:32
  • 1
    Set root in the .then function. Since your code runs asynchronously nodeIP may not be set by the time you are executing the var root = 'http://' + $rootScope.nodeIp + ':8080/'; – NTP Mar 13 '18 at 09:34
  • angular.module('Dashboard').factory('nodeServices', ['$http', '$q', '$location','$rootScope', function($http, $q, $location, $rootScope) { – af_khan Mar 13 '18 at 09:34

2 Answers2

1

api call are async. Hence $rootScope.nodeIpis undefined at the time when you using it out side the .then. You can use promise or the way I have done to get it working.

   var root = null;
   fetchIp().then(function(response){
        $rootScope.nodeIp = (response.length == 0 ? "localhost" : response[0]);
        root = 'http://' + $rootScope.nodeIp + ':8080/';

    });
Ved
  • 11,837
  • 5
  • 42
  • 60
0

You can use pattern async/await.

const request = async () => {
    const response = await fetchIp();
    $rootScope.nodeIp = (response.length == 0 ? "localhost" : response[0]);
};

request();

var root = 'http://' + $rootScope.nodeIp + ':8080/';

More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

coudy.one
  • 1,382
  • 12
  • 24