分開我有這樣的代碼:如何succesCallback從errorCallback在角控制器
app.factory('clients', ['$http', function ($http) {
var _getClient = function (clientId, callback) {
callback = callback || function() {};
$http({
method: 'GET',
url: '/simple_crm/web/api.php/client/'+clientId
}).then(function (data) {
callback(data);
}, function (error) {
callback(error);
});
};
return {
getClient: _getClient
};
}]);
,並在控制器
app.controller('ClientDetailCtrl', ['$scope', 'clients', '$routeParams', function ($scope, clients, $routeParams) {
$scope.user = {};
clients.getClient($routeParams.clientId,
function (data) {
//The block executes clientId is correct
$scope.user = data;
if (404 === data.status) {
//The block executes when Id does not exist and status page is 404
}
}
);
}]);
此代碼工作正常 - 隱藏/顯示在頁面上的div塊,但有可能隔離代碼塊錯誤,例如:
clients.getClient($routeParams.clientId,
function (data) {
//clientId is correct
$scope.user = data;
},
function (data) {
if (404 === data.status) {
//clientId does not exist
}
}
);
有沒有什麼可能什麼是最佳實踐?
你可以使用攔截器,更普遍的HTTP錯誤代碼。 https://docs.angularjs.org/api/ng/service/$http –