为angularjs中的变量赋值
为什么我不能用下面的代码为$rootScope赋值为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在之外使用
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){您解决了问题吗?