Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why move my $http calls into a service?

Currently I have calls like this all over my three controllers:

$scope.getCurrentUser = function () {
    $http.post("/Account/CurrentUser", {}, postOptions)
        .then(function(data) {
                var result = angular.fromJson(data.data);
                if (result != null) {
                    $scope.currentUser = result.id;
                }
            },
            function(data) {
                alert("Browser failed to get current user.");
            });
};

I see lots of advice to encapsulate the $http calls into an HttpService, or some such, but that it is much better practice to return the promise than return the data. Yet if I return the promise, all but one line in my controller $http call changes, and all the logic of dealing with the response remains in my controllers, e.g:

$scope.getCurrentUser = function() {
    RestService.post("/Account/CurrentUser", {}, postOptions)
        .then(function(data) {
                var result = angular.fromJson(data.data);
                if (result != null) {
                    $scope.currentUser = result.id;
                }
            },
            function(data) {
                alert("Browser failed to get current user.");
            });
};

I could create a RestService for each server side controller, but that would only end up calling a core service and passing the URL anyway.

like image 524
ProfK Avatar asked Jun 04 '16 11:06

ProfK


People also ask

What is the purpose of HTTP?

Hypertext Transfer Protocol (HTTP) is a method for encoding and transporting information between a client (such as a web browser) and a web server. HTTP is the primary protocol for transmission of information across the Internet.

What is difference between Get POST put Delete methods?

The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server. The PUT method replaces all current representations of the target resource with the request payload. The DELETE method deletes the specified resource.

What does an HTTP client do?

An HTTP Client. An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder . The builder can be used to configure per-client state, like: the preferred protocol version ( HTTP/1.1 or HTTP/2 ), whether to follow redirects, a proxy, an authenticator, etc.

What is HTTP and how does it work?

HTTP is a protocol for fetching resources such as HTML documents. It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser.


2 Answers

There are a few reasons why it is good practice in non-trivial applications.

Using a single generic service and passing in the url and parameters doesn't add so much value as you noticed. Instead you would have one method for each type of fetch that you need to do.

Some benefits of using services:

  • Re-usability. In a simple app, there might be one data fetch for each controller. But that can soon change. For example, you might have a product list page with getProducts, and a detail page with getProductDetail. But then you want to add a sale page, a category page, or show related products on the detail page. These might all use the original getProducts (with appropriate parameters).
  • Testing. You want to be able to test the controller, in isolation from an external data source. Baking the data fetch in to the controller doesn't make that easy. With a service, you just mock the service and you can test the controller with stable, known data.
  • Maintainability. You may decide that with simple services, it's a similar amount of code to just put it all in the controller, even if you're reusing it. What happens if the back-end path changes? Now you need to update it everywhere it's used. What happens if some extra logic is needed to process the data, or you need to get some supplementary data with another call? With a service, you make the change in one place. With it baked in to controllers, you have more work to do.
  • Code clarity. You want your methods to do clear, specific things. The controller is responsible for the logic around a specific part of the application. Adding in the mechanics of fetching data confuses that. With a simple example the only extra logic you need is to decode the json. That's not bad if your back-end returns exactly the data your controllers need in exactly the right format, but that may not be the case. By splitting the code out, each method can do one thing well. Let the service get data and pass it on to the controller in exactly the right format, then let the controller do it's thing.
like image 181
James Waddington Avatar answered Sep 28 '22 21:09

James Waddington


A controller carries out presentation logic (it acts as a viewmodel in Angular Model-View-Whatever pattern). Services do business logic (model). It is battle-proven separation of concerns and inherent part of OOP good practices.

Thin controllers and fat services guarantee that app units stay reusable, testable and maintainable.

There's no benefit in replacing $http with RestService if they are the same thing. The proper separation of business and presentation logic is expected to be something like this

$scope.getCurrentUser = function() {
  return UserService.getCurrent()
  .then(function(user) {
    $scope.currentUser = user.id;
  })
  .catch(function(err) {
    alert("Browser failed to get current user.");
    throw err;
  });
});

It takes care of result conditioning and returns a promise. getCurrentUser passes a promise, so it could be chained if needed (by other controller method or test).

like image 39
Estus Flask Avatar answered Sep 28 '22 23:09

Estus Flask