Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为angularjs中的变量赋值_Angularjs - Fatal编程技术网

为angularjs中的变量赋值

为angularjs中的变量赋值,angularjs,Angularjs,为什么我不能用下面的代码为$rootScope赋值 fetchIp().then(function(response){ $rootScope.nodeIp = (response.length == 0 ? "localhost" : response[0]); }); var root = 'http://' + $rootScope.nodeIp + ':8080/'; 它显示为“未定义”api调用是异步的。因此,$rootScope.nodeIp在之外使用

为什么我不能用下面的代码为$rootScope赋值

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

    });

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

它显示为“未定义”

api调用是异步的。因此,
$rootScope.nodeIp
之外使用时未定义。然后
。你可以用承诺或我所做的方式让它工作

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

    });

您可以使用模式async/await

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

request();

var root = 'http://' + $rootScope.nodeIp + ':8080/';
更多信息:

在.then函数中将此代码用于app.js或controllerSet根目录。由于代码异步运行,在执行var root='http://'+$rootScope.nodeIP+':8080/'时,可能不会设置nodeIP;angular.module('Dashboard').factory('NodeService'、['$http'、'$q'、'$location'、'$rootScope',函数($http、$q、$location、$rootScope){您解决了问题吗?