我在SPA中的ui路由器中使用Resolve功能在其他一些状态但由于某种原因在我的服务器仪表板状态,它在服务调用完成渲染之前调用模板。这导致了类型错误,因为我尝试使用在解析之前传递的值。
这是我的StateProvider:
.state('triangular.server-details', {
url: '/dashboards/Server/{hostName}',
templateUrl: 'app/examples/dashboards/server/dashboard-server.tmpl.html',
controller: 'DashboardServerController as serverDetails',
resolve:{
ServiceList:['$stateParams','ServerService', function($stateParams, ServerService){
return ServerService.getServices($stateParams.hostName);
}],
HostData:['$stateParams','ServerService', function($stateParams, ServerService){
return ServerService.getHost($stateParams.hostName);
}]
}
})
这是service.js中的getHost函数:
service.getHost = function(HostName){
var HostList = [];
$http.get('http://localhost:9000/Host/' + HostName).then(function(response){
var Data = response.data.recordset;
for (i = 0; i <= Data.length -1; i++){
HostList.push({
"HostName" :Data[i].HostName,
"address" :Data[i].Address,
"alias":Data[i].Alias,
"nagios":Data[i].Nagios,
"hoststatus":Data[i].Status,
"hoststatuscheck" : Data[i].LastCheck,
"hosticon" : Data[i].ShortStatus,
})
}
})
return HostList;
};
这是我的控制器:
DashboardServerController.$inject = ['ServiceList', 'HostData', '$scope'];
function DashboardServerController(ServiceList, HostData, $scope) {
var serverDetails = this;
serverDetails.ServiceList = ServiceList;
serverDetails.HostData = HostData;
console.log(serverDetails.HostData);
console.log(serverDetails.HostData[0].HostName);
}
当我第一次进入页面时,它会在控制台中打印HostData,但在尝试打印HostName时会出现类型错误。之后,api调用获取servicelist和Hostdata。如果我刷新页面我没有错误。
答案 0 :(得分:2)
如果您希望解决方案等待,您的getHost方法需要返回一个promise。 重构这样的事情:
service.getHost = function(HostName){
var HostList = [];
return $http.get('http://localhost:9000/Host/' + HostName).then(function(response){
var Data = response.data.recordset;
for (i = 0; i <= Data.length -1; i++){
HostList.push({
"HostName" :Data[i].HostName,
"address" :Data[i].Address,
"alias":Data[i].Alias,
"nagios":Data[i].Nagios,
"hoststatus":Data[i].Status,
"hoststatuscheck" : Data[i].LastCheck,
"hosticon" : Data[i].ShortStatus,
})
return HostList;
}
})
};