0

以下服務在控制器調用:響應數據在視圖中使用(AngularJS)

//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函數定義的值?或者,是否有可能在服務查詢中聲明?

回答

1

當錯誤函數被調用時,它什麼都不做,只是返回另一個錯誤函數。另一個問題是,它不知道在它的上下文變量$範圍,所以你必須通過它:

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

+0

謝謝..正確的解決方案是發送'$範圍'。 thaaaanks! – yuro

0

您將對象傳遞給一個名爲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; 
}; 

}

應該是: /這部分不工作/ 功能錯誤響應(錯誤){ 恢復功能(錯誤){$ = scope.msgError假; $ scope.errStatus = error.status; $ scope.statusText = error.statusText; $ scope.errMsgDetail = error.data.MessageDetail; }; }

相關問題