Differences between functions in Angular services and components: which one to use?

Our Angular application is made up of excel-like grids, with 20 components each containing a unique grid.

Every component includes a save() function that handles adding, editing, and deleting items. The save() function is quite large and resides in each component's .ts file due to the differences between them.

I decided to refactor the save() function starting with one component. However, I realized that it might be more efficient to centralize the function within a service, resulting in just one save() for the entire app instead of 20 individual ones. But there are potential drawbacks to this approach as well. I'm looking for insights from other Angular developers on why placing a function in a service could be beneficial compared to leaving it in each component.

PROS
- Simplify development - changes only need to be made in one place if refactoring is necessary. However, this may not always be the case:

CONS
- Development/maintenance may become more challenging, or not any easier. The significant differences between save() functions in each component could complicate matters.
- Decreased performance of save() due to additional switch case statements required to identify which component is calling save(). This performance impact may be subtle but still present.
- Consolidating and testing will be time-consuming - everything currently works fine, so breaking something would be unfortunate.

Any thoughts on this?

Answer №1

To develop a service for the functionality of saving information, one can employ an innovative strategy by introducing the concept of a BaseSave class. This class will contain protected methods (accessible to subclasses) that encompass all shared functionalities across diverse save scenarios.

Subsequently, individual injectable services can be created for each component, with each service extending the BaseSave class. While these services will utilize the protected methods provided by the base class, they will also incorporate their own specialized implementations of the public save() function.

In order to ensure robustness and reliability, it is imperative to conduct unit tests not only for the BaseSave class but also for every extended implementation derived from it.

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

Angular-Translate fails to function within a tag's attribute

For my project, I utilize angular-translate. One of the key definitions looks like this: { "paging":{ "first":"First", "last":"Last", "next":"Next2", "pre":"Previous" } } I implement it in the following way: <uib-pagination first-tex ...

Having an issue with the jQuery click function not functioning as expected in combination with

I have an HTML component with a button that is supposed to alert a message when clicked, but it's not working as expected. Currently, I have bound the button to a click function. Click here for demo HTML:- <div class="row row-bordered"> ...

Error message encountered in React upon form submission due to an invalid object

I encountered an issue when I input special characters in the password field, resulting in an invalid object error upon form submission. How can I address this type of error? Here is a React code snippet to consider: import React,{useState} from 'rea ...

Is it possible for me to insert a scope into the filter as well?

Recently, I created a task filter and I am facing an issue with editing the title text when another button is selected. I attempted to use a scope but that solution did not work. Does anyone have any suggestions or alternative solutions if the scope method ...

What is the best method for implementing click functionality to elements that share a common class using only pure JavaScript

I am struggling to figure out how to select specific elements with the same classes using only pure JavaScript (no jQuery). For example: <div class="item"> <div class="divInside"></div> </div> <div class= ...

Encountering an error while compiling the Angular 8 app: "expected ':' but got error TS1005"

As I work on developing an Angular 8 application through a tutorial, I find myself facing a challenge in my header component. Specifically, I am looking to display the email address of the currently logged-in user within this component. The code snippet fr ...

Acquiring radio button input in PHP

I have 2 radio buttons within a form, <label><input type="radio" onclick="this.form.submit()" name="shfaq<?php echo $i; ?>" value="1" id="radiobuttonsondazh_0" <?php if($result['live']==1) echo 'checked'; ?> /> ...

Passing variables by reference in JavaScript allows for direct manipulation of

Is there a JavaScript equivalent to PHP's method of passing variables by reference? [PHP]: function addToEnd(&$theRefVar,$str) { $theRefVar.=$str; } $myVar="Hello"; addToEnd($myVar," World!"); print $myVar;//Outputs: Hello World! If possible, h ...

What's the best method for updating a div on a webpage to display the most current information from the database?

In my small blog project, I have implemented a viewcount feature that tracks the number of times a particular post has been viewed. However, the issue I am facing is that the value of viewcount does not update unless the entire page is refreshed. To addres ...

``Implementing a method to save the output of an asynchronous request in a global variable for future manipulation

It's been a week and I still can't figure this out. Being new to front-end development, I'm struggling with storing the response from subscribe in a global variable for future use. ngOnInit(): void { this.http.get<APIResponse>('ur ...

Encode a variable into base64 using the Buffer module in node.js

Attempting to convert a variable from an HTTP parameter to base64 using node.js and Buffer. Code snippet: var http = require("http"); var url = require("url"); http.createServer(function(req, res) { var parsedUrl = url.parse(req.url, true); var que ...

Is there a way for me to retrieve the locator value of a webelement?

How can I retrieve the selector value used in a selenium webelement in javascript? Let's say I have the following object: var el = browser.driver.findElement(by.id('testEl')); I want to extract the text 'testEl' from this object ...

Encountering an Issue with Missing Registration Error When Making HTTPPost Requests to GCM in Google Apps Script

I am attempting to send an HTTP POST request to the GCM server using Google Apps Script. I have both the device ID and the necessary credentials. Below is the code I am currently using: function doThat(){ var url = "https://android.googleapis.com/gcm/se ...

Add elements from one array into designated positions within another array

Is there a way to extract the days and months from the current week and store it in an array within a specific field of an object? I need to be able to later iterate through this array to display the data. I am unsure on how to achieve this. <div v-for ...

Properly citing JQuery references

Attempting to incorporate Jquery for the first time, I've encountered an issue. Specifically, I am utilizing VS 2013, asp.net, and VB. Within my head tag, the structure is as shown below. <head runat="server"> <title></title> ...

Trouble persisting in loading PopperJS and Bootstrap through RequireJS, despite following the suggested PopperJS version

Struggling to load jquery, popperjs, and bootstrap (v4-beta) using requirejs, I'm consistently encountering this error in the console: Uncaught Error: Bootstrap dropdown require Popper.js (https://popper.js.org) at bootstrap.js:6 at bootstrap ...

Mocking Multiple Instances of Classes in Jest

I am currently working on a project where I have a class that creates multiple instances of the same object. I am trying to mock this behavior in jest, but I keep encountering an error specifically for the second instance creation test. Error: expect(rece ...

React Error: Attempting to use objects as a React child is not permitted

An error occurred: Objects are not a valid React child element. labelList contains an array of objects with sample data provided below. I'm attempting to iterate over these objects in order to create a separate row for each object's data. I&apos ...

What are some alternative methods for concealing certain content in my gallery without using java script?

Currently, I am utilizing a JavaScript "show more, hide less" button on my page. However, I am facing an issue where I can't use the same button multiple times on the same page. I tried changing the ID, but it didn't work for me. I suspect I may ...

Remove the initial DIV element from the HTML code

I have created a unique chat interface by combining JScript, php, and jquery. The chat messages are saved in an HTML document that gets displayed in the text area. Each user input message is contained within its individual div tag: <div>Message</ ...