How to avoid repetition of .then() and .catch() after $http requests?

南笙酒味 提交于 2019-12-08 19:42:35

Why not just write the functions once and apply them to each callback in the service?

Something like:

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);
    };
});

Also note you can use then(successcallback, errorcallback, notifycallback) to shorten your code even further than using then/catch.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!