Where should data processing be conducted: in the service or controller layer?

Here's a question regarding the best practices for organizing code.

I'm fetching data from an API using $resource and I need to manipulate it before displaying it on the view.

My dilemma is at which stage should I process the data? My current belief is that it should be handled in the service, but I also prefer handling the actual AJAX call within the controller.

Currently, I am injecting the service and utilizing functions like CdnService.sumOfVolumeRequest(response) to process the data.

Is my approach correct or is there a more effective way?

Service:

function updateVolumeRequest() {
    var params = {
      metric: "size",
      tStart: convertUtcToEpoch(SearchCriteria.criteria.dateFrom),
      tEnd: convertUtcToEpoch(SearchCriteria.criteria.dateTo)
    };
    return params;
  }

  function volumeRequest() {
    return CdnAnalyticsFactory.statsByDimension({
          accountId: Token.UserInfo().Id
        },
        updateVolumeRequest())
      .$promise;
  }

Controller:

function getData() {
    var data;

    CdnService.sizeRequest(SearchCriteria.criteria.dateFrom, SearchCriteria.criteria.dateTo)
      .then(function onSucess(response) {
        data = CdnService.sumOfVolumeRequest(response)

      });

}

Answer №1

For additional information, please consult the Angular Style Guide by John Papa

When it comes to handling data operations and data interaction, consider refactoring your logic into a factory. Let data services handle XHR calls, local storage, caching in memory, and other data-related tasks.

The main question to ponder is: Should the service be modular? Should it seamlessly integrate with multiple controllers while maintaining consistent functionality?

If you prefer the service to be self-contained, then incorporating data manipulation within the service itself is a better approach. The goal is for the service to consistently provide data in the desired format each time it's called. Moving some functionality outside may lead to redundant code repetition, contradicting the DRY principle.

Ultimately, it’s essential to determine how much data manipulation should occur within the service versus externally.

If the code in your controller is specific to that controller's logic, it’s acceptable to keep it there. However, try to avoid including code that would need to be duplicated every time the service is utilized.

Answer №2

The decision would vary based on the specific circumstances.

In cases where the logic is applicable across different views, it may be beneficial to relocate the code to a service. This would allow for easier reuse in various controllers. However, if the logic is tailored to a particular view, it might be more appropriate to include it in a controller instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript/DOM - What sets apart a "CSS Selector" from an attribute?

When it comes to excluding declarative event handlers: <a href='#' onclick=<handler> ... /> Is there a significant difference between an Attribute and a CSS Selector? For example, if I define my own attribute: <a href='#&a ...

Showing JSON information on a web browser

Here is a snippet of JSON data that I am working with: {"earthquakes":[{"datetime":"2011-03-11 04:46:23","depth":24.39999999999999857891452847979962825775146484375,"lng":142.36899999999999977262632455676794 ...

Identifying a specific field in a dynamically generated React.js component: Best practices

Currently, I am in the process of developing a form with an undetermined number of sensor fields. The front end has been successfully implemented and now my focus is on extracting user information from these dynamically generated component fields. Here is ...

What is the most strategic way to conceal this overlay element?

Currently, the website I'm developing features a series of navigation elements at the top such as "Products" and "Company." Upon hovering over the Products link, an overlay displays a list of products with clickable links. Positioned at the top of the ...

What steps can be taken to design a unique CSS pop-up that triggers upon page load, limited to one appearance per visitor every week

I have the following code snippet that allows me to display a pop-up either by clicking on the link or hovering over it. I am looking to modify it so that the pop-up opens when the page loads and restrict it to open only once per visitor per week. As some ...

Is there a way to verify the functionality of DigitalOcean features using doctl before transitioning to a live environment?

As a newcomer to using DigitalOcean Functions, I have set up some JavaScript namespaces using the doctl serverless command. My main query is regarding testing DigitalOcean functions locally before deploying them to production. Is there a way to do this wit ...

I encountered an error while attempting to import a file into Firebase Storage

I've been struggling to upload files from Firebase Storage and encountering errors despite reading the documentation and various blogs on the topic. I'm looking for the most effective approach to resolve this issue. import { storage } from ' ...

Discovering and updating a DOM element with a rejuvenating touch: Angular JS

Although not very experienced with Angular JS, here's what I currently have and what I aim to achieve: <div ng-app="MyApp" ng-controller="appController"> <div class="input-group"> <input class="form-control enableEnter" type=" ...

Differences in performance between Angular and JQuery_execution times

I am facing an issue on my dynamically populated Angular page. Angular sends a request to the backend using $http.get to retrieve data which then populates attributes of a controller. For example, when I call $http.get('/_car_data'), the JSON re ...

Invoke a codebehind function using jQuery

I am encountering an issue while trying to complete a simple task. I am attempting to pass values to a code behind method, perform some calculations, and then return the result. Initially, I started with a test method but have not been successful in making ...

Need help tackling this issue: getting the error message "Route.post() is asking for a callback function, but received [object Undefined]

I am currently working on implementing a new contactUs page in my project that includes a form to store data in a mongoDB collection. However, after setting up all the controller and route files and launching the app, I encountered an error that I'm u ...

The functionality of Angular and ui-router is currently experiencing technical difficulties

Hey there, I'm currently experimenting with a basic application using Angular and UI-Router. However, I've run into some issues as it doesn't seem to be functioning properly. When I check in Chrome, there are no errors displayed in the cons ...

Retrieving selected item values in Angular 2 using ng2-completer

Recently, I decided to experiment with a new autocompleter tool that is unfamiliar to me: https://github.com/oferh/ng2-completer. I successfully imported it and it seems to be functioning properly. My current goal is to retrieve the values of the selecte ...

Provide a value for a secondary select option parameter

I need to retrieve the university ID for use in another select option, which will display my college list under a specific university from a MySQL database. However, I am struggling to find the right approach. I want to pass fetch.university_id as a parame ...

Implementing a 10-second alert display in selenium

Task at Hand: I need to display the alert on my page for a few seconds to allow reading. Is there any function in Selenium Web-driver that can help with this? I am new to automation and have been learning about explicit waits. I tried using explicit wait ...

jQuery unable to locate elements or update class following AJAX response

My jQuery.on() event functions are working great when bound to specific elements like "a.my-link". However, I have one function that is bound to the document or body and then traverses multiple elements with the same class attribute. Certain lines in this ...

Using identical CSS styles across various classes in material UI

Three classes have been defined with identical CSS properties. const useStyles = makeStyles((theme) => ({ classA: { color: 'green' }, classB: { color: 'green' }, classC: { color: 'green' } }) Is there a way to combin ...

The datatable's api.draw function seems to be malfunctioning. Does anyone have suggestions on how to properly set up the columns and display each

Why is the pagination not showing when I append each row in my code without using the draw method? How can I define the column and render rows with the defined column? What mistake am I making here? //ignore this repeated section . Currently appending eac ...

Resolve the issue of autofill data overlapping with field labels

My form incorporates the Canada Post AddressComplete tool, which functions similarly to Google Maps Autocomplete. As you type your address, suggestions appear in a drop-down menu. However, after selecting an address, the text in the Postal Code and City f ...

What is the best way to implement client side validation for a related input field using JavaScript in a Rails application?

Struggling to find a solution for adding a validation check for a dropdown list that is dependent on another input selection in a different form. It seems like database validation may be necessary, but I'm unsure of the best approach. Any suggestions ...