我正在使用AngularJS前端和ASP.NET Web API后端的项目。
我有一个调用Web API的服务并返回一堆JSON数据。我试图在我的控制器中访问该数据,但是我得到一个错误,说明我之后的属性是未定义的!我之后的属性是RegisteredKeeperName。
$scope.getCrateDetails = function (result, isInsert) {
$scope.showCrateDetails = true;
getCrateDetails();
if (!$scope.premiumCrate.RegisteredKeeperName.toLowerCase().indexOf("Green Farm") > -1) {
$scope.calloutClass = 'callout-danger';
$scope.calloutMessage = 'We (Green Farm) cannot provide this service with the necessary documents.';
} else {
$scope.calloutMessage = 'All is good!';
}
};
即使我打印出$scope
,我也可以看到我之后填写正确信息的属性!
{{premiumCrate.RegisteredKeeperName}}
我的服务代码如下:
function getCrateDetails() {
// service call goes here.
stockData.GetCrateDetails($scope.premiumCrate.Id).then(
function (cData) {
$scope.premiumCrate = cData;
},
function () {
});
};
答案 0 :(得分:1)
getCreateDetails
是异步通话(您在返回和分配数据之前尝试使用数据),您应return
使用.then
进行调用并访问它在控制器中,像这样:
function getCrateDetails() {
return stockData.GetCrateDetails($scope.premiumCrate.Id).then(function (cData) {
return cData.data;
}, function () {
});
};
拨打电话:
getCrateDetails().then(function(data) {
console.log(data); //hey data!
$scope.premiumCrate = data;
if (!$scope.premiumCrate.RegisteredKeeperName.toLowerCase().indexOf("Green Farm") > -1) {
$scope.calloutClass = 'callout-danger';
$scope.calloutMessage = 'We (Green Farm) cannot provide this service with the necessary documents.';
} else {
$scope.calloutMessage = 'All is good!';
}
});