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

Guide to verifying the property value following mocking a function: Dealing with Assertion Errors in Mocha

Based on a recommendation from a discussion on this link, I decided to mock the readFileSync function and then mocked my outer function. Now, my goal is to verify whether the variable's value has been set as expected. file.js const fs1 = require ...

The transition from Vuetify3's VSimpleTable to VTable is ineffective and unsuccessful

The v-simple-table component has been renamed to v-table Old code that was using v-simple-table may not work correctly after the renaming. It is recommended to use v-data-table with the same data, as it works correctly. Here's the full page code: Yo ...

How to Use Jquery to Retrieve the Selected Option Value and Append a Parameter

I am attempting to expand the value by adding "&fullpage=true" <select name="navMenu" onchange="go(this.options[this.selectedIndex].value)"> <option value="-">Choose</option> <option value="page.html&amp;nyo=0" class="ccbnLnk" ...

Exploring the Power of an Enumerator in JavaScript

I'm in the process of converting the following VBScript code to JavaScript: Sub GxUIProxyVB_OnLogon Dim EntityProxy For Each EntityProxy In GxUIProxyVB.ListEntityProxy MsgBox EntityProxy.Name Next End Sub This code is an e ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Dynamic anime-js hover animation flickering at high speeds

I have implemented the anime-js animation library to create an effect where a div grows when hovered over and shrinks when moving the mouse away. You can find the documentation for this library here: The animation works perfectly if you move slowly, allow ...

Executing an Ajax form submission in React.js

Currently in the process of developing my initial application using React.js and aiming to send a contact form via email with Ajax. I've been referencing a solution from this source: . Unfortunately, only parts of the full component file are available ...

Failed Cross-Origin Request Sharing in AngularJS 1.4

I'm currently working with AngularJS version 1.4.3 and here is the code snippet I am using: angular .module('app', []) .run(run); function run($http) { a = $http({ method: "GET", url: 'http://127.0.0 ...

Using Javascript to Pass Variables to Ajax with getElementById

Struggling to figure out how to effectively pass a Javascript Variable to Ajax and then post it to PHP? While both the Javascript and PHP code are functioning as expected, the challenge lies in transferring the Javascript Variable to Ajax for subsequent ...

What counterpart in JavaScript resembles the .NET Standard Class Library?

As someone transitioning from a background in .NET to learning Vue.js, I'm curious about the best way to create classes that handle business logic for me. Specifically, I want to be able to fetch information from an API, format it as needed and easily ...

How can I connect the box using the Interactive Picture jQuery tool?

When using the Interactive picture jQuery, I have the following code snippet within my document: jQuery(document).ready(function(){ $( "#iPicture6" ).iPicture({ animation: true, animationBg: "bgblack", animationType: "ltr-slide ...

What is the best method for me to filter the values in my array?

I need to add a value to an array based on certain conditions. My code looks something like this: var newEmployee = []; $scope.employees = [{'id':1, 'new':true},{'id':2, 'new':false}{'id':3, 'new&apo ...

Encountering an undefined property error while trying to access index '0' in Angular 6 with Angular Material's mat-radio-group component, specifically when attempting to set a dynamic variable within

Currently, I am working with Angular 6 and Angular Material. My project involves a dynamic list of polls with various options. I am attempting to display the selected option using two-way data binding. However, due to the dynamic nature of my list, I have ...

EaselJS - Utilizing multiple canvases with varying frame rates

Currently, I am exploring EaselJS by creating two animation instances using sprite sheets on two separate canvases positioned at different locations but with the same z-index. The issue I am facing is that these instances are not layered properly. My setup ...

Decode JSON and generate a user-friendly Array

My aim is to extract and organize the JSON data received from an external API into a custom array. However, I am encountering two challenges: I'm struggling to access the value labeled #2 under "Meta Data". If I want to extract the first array n ...

What is the best method for transmitting a PHP object via Ajax using JSON format?

Here is the ajax code snippet I am currently using: $.ajax({ type: 'post', url: '/conversation/test', data: { conversation: JSON.stringify(<?php echo json_encode($conversat ...

Ensure that the div remains fixed at the bottom even when multiple items are added

Following up on the previous question posted here: Sorting divs alphabetically in its own parent (due to many lists) I have successfully sorted the lists alphabetically, but now I need to ensure that a specific div with a green background (class: last) al ...

Do I need to use the "--save" flag in npm to add dependencies to the "package.json" file?

Do I really need to use the "--save" flag in order to add an installed dependency to the "package.json" file? I conducted a test without the "save" flag and found that the package was still added to the "dependencies" section. It seems like it is the defa ...

AJAX function in Chrome console is throwing an error message stating "Unexpected Token }"

Dealing with this issue has been quite unusual for me. I've spent the last 3 days trying to troubleshoot it, but now it's no longer bothering me. The situation involves a button and a textbox that sends the data from the textbox to a PHP page whe ...

Is it possible to run my NPM CLI package on CMD without needing to install it globally beforehand?

I've created a new NPM package, complete with its own set of CLI commands. Let's call this package xyz, and let's imagine it's now live on npmjs.com Now, picture a user who installs this package in their project by executing npm insta ...