function forgot(email) {
$scope.myPromise = Auth.forgot({'email': email}).then(function (response) {
if (response.data.validator || response.data.errors) {
return;
}
$('#modalConfirmation').modal('show');
});
}
function confirmation(token) {
Auth.confirmation({'token': token.trim()}).then(function (response) {
if (response.data.validator || response.data.errors) {
return;
}
$http.defaults.headers.common.Authorization = 'Bearer ' + response.data.token;
$('#modalConfirmation').modal('hide');
$('#modalReset').modal('show');
});
}
function reset(password) {
Auth.reset({'password': password}).then(function (response) {
if (response.data.validator || response.data.errors) {
return;
}
$location.path('/login');
});
}
看看是否重复每个。然后。有什么办法让它变得更好?
答案 0 :(得分:0)
我猜你可能会从中间件中抛出错误:
function checkForFailure(response) {
if (response.data.validator || response.data.errors) {
throw new Error('Validation failed, or error occurred');
}
}
function forgot(email) {
$scope.myPromise = Auth.forgot({'email': email})
.then(checkForFailure)
.then(function (response) {
$('#modalConfirmation').modal('show');
});
}
function confirmation(token) {
Auth.confirmation({'token': token.trim()})
.then(checkForFailure)
.then(function (response) {
$http.defaults.headers.common.Authorization = 'Bearer ' + response.data.token;
$('#modalConfirmation').modal('hide');
$('#modalReset').modal('show');
});
}
function reset(password) {
Auth.reset({'password': password})
.then(checkForFailure)
.then(function (response) {
$location.path('/login');
});
}
当然,您可以通过在使用Auth
方法时创建一种代理来添加额外的抽象级别,该方法始终将当时的中间件与checkForFailure
绑定,但这可能有点过分。< / p>
答案 1 :(得分:0)
// New Function
function getAuthAction(actionName, parameterObject, callback){
return Auth[actionName].call(Auth, parameterObject).then(function (response) {
if (response.data.validator || response.data.errors) return;
callback(response);
});
}
// Usage
function forgot(email) {
$scope.myPromise = getAuthAction('forgot', {'email': email}, function (response) {
$('#modalConfirmation').modal('show');
});
}
function confirmation(token) {
getAuthAction('confirmation', {'token': token.trim()}, function (response) {
$http.defaults.headers.common.Authorization = 'Bearer ' + response.data.token;
$('#modalConfirmation').modal('hide');
$('#modalReset').modal('show');
});
}
function reset(password) {
getAuthAction('reset', {'password': password}, function (response) {
$location.path('/login');
});
}