我在我的角度應用一個簡單的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請求後,重複相同的。那麼()和.catch()函數。根據DRY原則,我可以避免這種重複嗎?
我不明白這些回調是做什麼的...... – elclanrs 2015-02-23 05:01:20
爲什麼不在控制器中捕獲錯誤(或者使用'userAPI'服務的地方)? – aarosil 2015-02-23 05:06:08
此外,更重要的是,爲什麼你不使用__ [$資源](https://docs.angularjs.org/api/ngResource/service/$resource)__爲此? – aarosil 2015-02-23 06:13:29