我使用Angular通过$http
服务发送post请求。在发送帖子请求之前,我正在Angular中对表单进行所有数据验证。然而,我正在用PHP验证用户是否已经存在于数据库中。如何有目的地调用错误(php文件中的),以便触发Angular错误回调而不是成功回调?我应该故意抛出一个异常吗?
如果目的是抛出异常,那么异常消息是否会传递到Angular error
回调函数的data
参数中?
根据对我的问题的评论,我只是对我的代码做了以下操作:
if (duplicateUsers($username) > 0) {
return http_response_code(400); // successfully generated an error in
// the $http AngularJS servicces
} else {
// other code
}
您可以将您的承诺连锁起来。第一个承诺将检查成功内容,这也是您可以抛出异常的地方。这将导致后续承诺返回失败。
下面是一个jsbin示例。
angular
.module('app', [])
.run(function($http) {
var from$http = $http
.get('www.google.com') //makes a request to www.google.com
.then(function(response) {
console.log('data was successfully retrieved from google');
throw "from success handler"; //if has error, then throw "duplicated user"
});
from$http.then(function() { // this then block is handling the previous exception
console.log('this success block is never called');
}, function() {
console.log('inside error block even tho success was returned from www.google.com');
});
});