【发布时间】:2015-02-23 04:57:29
【问题描述】:
我的 Angular 应用中有一个简单的 userAPI 服务:
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 原则避免这种重复吗?
【问题讨论】:
-
我看不出那些回调有什么作用...
-
为什么不在控制器中捕获错误(或在任何你使用
userAPI服务的地方)? -
另外,更重要的是,你为什么不使用 $resource 呢???
标签: javascript angularjs promise dry