在视图中使用值的响应数据(AngularJS)

Response data in values to use in view (AngularJS)

本文关键字:数据 响应 AngularJS 视图      更新时间:2023-09-26

在控制器中调用以下服务:

//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'
   }, {}),
}

您可以在服务代码中看到,错误响应不会在视图中调用。我使用的错误消息从响应头分别后端。如果请求失败,则必须显示如下代码所示的警告框:

<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.

将对象传递给名为error的参数,但随后将其引用为err。这只是个打字错误。

/*This part doesn't work*/
function errorResponse(error) {
   return function (error) {
      $scope.msgError = false;
      $scope.errStatus = err.status;
      $scope.statusText = err.statusText;
      $scope.errMsgDetail = err.data.MessageDetail;
 };

}

应该是:/这个部分不工作/函数errorResponse(error) {返回函数(错误){美元的范围。msgError = false;美元的范围。errStatus = error.status;美元的范围。statusText = error.statusText;美元的范围。errMsgDetail = error.data.MessageDetail;};}