如何避免在$ http请求后重复.then()和.catch()? [英] How to avoid repetition of .then() and .catch() after $http requests?
本文介绍了如何避免在$ http请求后重复.then()和.catch()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的角度应用程序中有一个简单的userAPI服务:
I have a simple userAPI service in my angular app:
app.service('userAPI', function ($http) {
this.create = function (user) {
return $http
.post("/api/user", { data: user })
.then(function (promise) { return promise.data })
.catch(function (error) { return error.data })
}
this.read = function (user) {
return $http
.get("/api/user/" + user.id)
.then(function (promise) { return promise.data })
.catch(function (error) { return error.data })
}
this.update = function (user) {
return $http
.patch("/api/user/" + user.id, { data: user })
.then(function (promise) { return promise.data })
.catch(function (error) { return error.data })
}
this.delete = function (user) {
return $http
.delete("/api/user/" + user.id)
.then(function (promise) { return promise.data })
.catch(function (error) { return error.data })
}
})
正如你所看到的,我在每个$ http请求之后重复相同的.then()和.catch()函数。我可以根据DRY原则避免这种重复吗?
As you can see, i am repeating same .then() and .catch() functions after each of my $http requests. Ho can i avoid this repitition according to DRY principle?
推荐答案
为什么不写一次函数并将它们应用到每个回调中服务?
Why not just write the functions once and apply them to each callback in the service?
类似于:
app.service('userAPI', function ($http) {
var success = function (response) { return response.data; },
error = function (error) { return error.data; };
this.create = function (user) {
return $http
.post("/api/user", { data: user })
.then(success, error);
}
this.read = function (user) {
return $http
.get("/api/user/" + user.id)
.then(success, error);
};
this.update = function (user) {
return $http
.patch("/api/user/" + user.id, { data: user })
.then(success, error);
};
this.delete = function (user) {
return $http
.delete("/api/user/" + user.id)
.then(success, error);
};
});
另请注意,您可以使用然后(successcallback,errorcallback,notifycallback)
比使用then / catch更进一步缩短你的代码。
Also note you can use then(successcallback, errorcallback, notifycallback)
to shorten your code even further than using then/catch.
这篇关于如何避免在$ http请求后重复.then()和.catch()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文