问题描述
限时送ChatGPT账号..如何拒绝或失败成功的 $http.get() 承诺?当我收到数据时,我会针对它运行一个验证器,如果数据没有必需的属性,我想拒绝该请求.我知道我可以在承诺解决后做,但尽快拦截错误似乎是个好主意.我熟悉 $q 的好处,但真的想继续使用 $http.
How do I reject or fail a successful $http.get() promise? When I receive the data, I run a validator against it and if the data doesn't have required properties I want to reject the request. I know I can do after the promise is resolved, but it seems like a good idea to intercept errors as soon as possible. I'm familiar with the benefits of $q, but really want to continue using $http.
推荐答案
您可以通过将 $q.reject("reason")
返回到下一个链接的 .then<来拒绝任何承诺/代码>.
You can reject any promise by returning $q.reject("reason")
to the next chained .then
.
与 $http
相同,它返回一个 promise - 这可能如下:
Same with $http
, which returns a promise - this could be as follows:
return $http.get("data.json").then(function(response){
if (response.data === "something I don't like") {
return $q.reject("bad data");
}
return response.data;
}
这可以简单地在一个服务中完成,它使用上面指定的 .then
预先处理响应,并返回一些数据 - 或拒绝.
This could simply be done within a service, which pre-handles the response with the .then
as specified above, and returns some data - or a rejection.
如果您想在应用程序级别执行此操作,可以使用 $http 拦截器 - 这只是一个提供处理 $http 请求和响应的功能的服务,并允许您拦截响应并返回响应 - 相同或修改 - 或响应的承诺,包括拒绝.
If you want to do this at an app-level, you could use $http interceptors - this is just a service that provides functions to handle $http requests and responses, and allows you to intercept a response and return either a response - same or modified - or a promise of the response, including a rejection.
.factory("fooInterceptor", function($q){
return {
response: function(response){
if (response.data === "something I don't like") {
return $q.reject("bad data");
}
return response;
}
}
});
与上述相同的想法 - 除了在不同的层面上.
Same idea as above - except, at a different level.
请注意,要注册拦截器,您需要在 .config
中执行此操作:
Note, that to register an interceptor, you need to do this within a .config
:
$httpProvider.interceptors.push("fooInterceptor");
这篇关于如何使成功的 Angular JS $http.get() 承诺失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论