Controller 中调用以下服务:
//Controller
$scope.groups = CrudService.getAllGroups();
此服务返回数据库中的所有组。那么接下来,服务代码如下所示:
//Service (CrudService)
function getAllGroups() {
return ResService.group.query(
successResponse,
errorResponse);
}
function successResponse(resp) {
return resp;
}
/*This part doesn't work*/
function errorResponse(error) {
return function (err) {
$scope.msgError = false;
$scope.errStatus = err.status;
$scope.statusText = err.statusText;
$scope.errMsgDetail = err.data.MessageDetail;
};
}
/**************************/
//Nested Service (ResService)
return {
group: $resource(baseUrl + '/api/group/:Id', {
Id: '@Id'
}, {}),
}
您可以在服务代码中看到,错误响应不会在 View 中调用。我分别使用来自响应 header 和后端的错误消息。如果请求失败,则必须显示警报框,如以下代码所示:
<div>
<alert ng-hide="msgError" type="alert alert-danger" close="closeAlert()">
<p><b>{{ statusTitle }}</b>: <i>{{ errStatus }} - {{ statusText }}</i></p>
<p><strong>{{ msgTitle }}</strong>: <i>{{ errMsgDetail }}</i> <i>{{ msgException }}</i></p>
</alert>
</div>
有人知道如何访问或正确定义 errorResponse
函数中的值吗?或者,是否可以在服务查询中声明?
最佳答案
当调用错误函数时,它什么也不做,只是返回另一个错误函数。另一个问题是它不知道其上下文中的变量 $scope,因此您必须传递它:
$scope.groups = CrudService.getAllGroups($scope);
function getAllGroups($scope) {
return ResService.group.query(
successResponse,
errorResponse($scope));
}
function errorResponse($scope) {
return function(error) {
$scope.msgError = false;
$scope.errStatus = error.status;
$scope.statusText = error.statusText;
$scope.errMsgDetail = error.data.MessageDetail;
}
}
还有一个拼写错误,你写了err.
,但应该是error.
。
关于javascript - 要在 View 中使用的值中的响应数据 (AngularJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32972077/