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

China☆狼群 提交于 2019-12-08 04:03:35

问题


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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/28667147/how-to-avoid-repetition-of-then-and-catch-after-http-requests

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