$http/$q/promise 个问题(在 Angular 中)
$http/$q/promise Questions (in Angular)
我似乎无法理解 $q/$http 何时应该触发 onReject
块。
假设我有一个基本电话:
$http.get('/users')
.then(function(res) {
return res.data;
}, function(err) {
console.log(err);
});
如果我得到 500 Internal Server Error
,我将进入 onSuccess
街区。根据我对承诺的微薄理解,我猜这似乎是正确的,因为我在技术上确实得到了回应?问题是 onSuccess
块似乎放错了一堆
if(res.status >= 400) {
return $q.reject('something went wrong: ' + res.status);
}
这样我的 onReject
块就会得到 运行。这是它应该工作的方式吗?大多数人是在 onSuccess
区块中处理 400 多个状态,还是他们 return 拒绝了强制 onReject
区块的承诺?我是否缺少更好的处理方法?
我尝试在 httpInterceptor
中执行此操作,但我找不到从此处 return 拒绝承诺的方法。
this.responseError = function(res) {
if(res.status >= 400) {
// do something
}
return res;
};
你的成功块不会被击中。试试看,如果错误代码 > 300,错误块就会命中。
$http.get('/users').success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
您可以在拦截器中而不是在回调中处理这些。
在您的 app.config 中,您可以将 $httpProvider 配置为如下所示:
$httpProvider.interceptors.push(['$q', function ($q) {
return {
request: function (config) {
//do something
return config;
},
responseError: function (response) {
if (response.status === 401) {
//handle 401
}
return $q.reject(response);
}
};
}]);
我似乎无法理解 $q/$http 何时应该触发 onReject
块。
假设我有一个基本电话:
$http.get('/users')
.then(function(res) {
return res.data;
}, function(err) {
console.log(err);
});
如果我得到 500 Internal Server Error
,我将进入 onSuccess
街区。根据我对承诺的微薄理解,我猜这似乎是正确的,因为我在技术上确实得到了回应?问题是 onSuccess
块似乎放错了一堆
if(res.status >= 400) {
return $q.reject('something went wrong: ' + res.status);
}
这样我的 onReject
块就会得到 运行。这是它应该工作的方式吗?大多数人是在 onSuccess
区块中处理 400 多个状态,还是他们 return 拒绝了强制 onReject
区块的承诺?我是否缺少更好的处理方法?
我尝试在 httpInterceptor
中执行此操作,但我找不到从此处 return 拒绝承诺的方法。
this.responseError = function(res) {
if(res.status >= 400) {
// do something
}
return res;
};
你的成功块不会被击中。试试看,如果错误代码 > 300,错误块就会命中。
$http.get('/users').success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
您可以在拦截器中而不是在回调中处理这些。
在您的 app.config 中,您可以将 $httpProvider 配置为如下所示:
$httpProvider.interceptors.push(['$q', function ($q) {
return {
request: function (config) {
//do something
return config;
},
responseError: function (response) {
if (response.status === 401) {
//handle 401
}
return $q.reject(response);
}
};
}]);