Exploring the relationship between classes and objects within Angular

Is it problematic to use traditional classes and objects in Angular code? For instance, when refactoring to separate specific logic from messy code, I often create a separate file like logic-handler.ts and define a class like so...

export class LogicHandler {
  var1: Obj1;
  var2: Obj2;

  constructor(/* ... */) { /* ... */ }
}

I then instantiate an object of this class within the component.ts file to handle the logic. However, a senior member of my team always expressed reluctance towards this approach as he was unsure of how Angular handles new instances of LogicHandler.

Should we be concerned about this? Is there a valid reason for worry?

I am hoping someone can address my concerns or offer a better solution to this issue. Personally, I find my method simpler and more straightforward for testing purposes.

Answer №1

As mentioned by @browsermator in the comments of the question, there is no problem with using regular classes for purposes other than Angular components.

Your application code is written in normal TypeScript (and JavaScript), which means that classes are fully supported.

During the AOT phase, Angular identifies and wraps all classes adorned with @Component, linking them to templates and styles, and managing instantiation at runtime (new...). This same process applies to services and modules as well.

So, unless you specifically decorate your regular classes with Angular features, Angular will not interfere with them, allowing you to use them as you would in a non-Angular environment.

By the way, chances are you are already instantiating such normal classes, like with new Date() (even if done through libraries like date-fns), demonstrating that there are no compatibility issues with Angular.

Answer №2

After delving deeper into the subject matter, I realized that the flaw in this approach lies in the creation of a tight coupling between my component and the LogicHandler.

As a result, when it comes to testing my component, it becomes challenging to mock this object since the dependency is hardcoded within the component instead of being injected. This violates the principle of dependency inversion (DIP) outlined in the SOLID principles.

The optimal solution in this scenario would be to design the LogicHandler as a service and inject it into the component through its constructor.

To summarize, it is essential never to directly instantiate an object within another class, as an object should not be burdened with handling its own dependencies.

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

Error loading ngs-boostrap in angular2: issues encountered during initialization

Attempting to implement a dropdown menu using ng2-bootstrap component, but encountering an error upon access: Error message received: Failed to load resource: the server responded with a status of 404 (Not Found) Steps taken so far: 1) Installed ng2-boo ...

Combine all the missing observables in RxJS into a single array

In my code, I am creating a NavBar with items that may require fetching extra information from an API and adding it to the subtitle field. I want to transform this into an Observable<NavItem[]> so that it can be rendered using an Async Pipe. Curren ...

Update and send back variable on the spot

I'm interested in learning the syntax for creating an inline function that can accept a parameter, perform a simple modification on it, and return it all in a single line. Here's an example: (input) => { input.status = 'complete'; ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Testing Angular components with Jasmine where ViewChild components are nested within each other

I encountered an issue while unit testing the ionViewDidLeave function on DashboardPage: @Component({ template: '<app-dashboard-slider #dashboardSlider></app-dashboard-slider>', selector: 'app-dashboard', }) export class ...

Encountering difficulties when attempting to start a new project in Angular

I am encountering an issue while trying to create new in Angular, using version 6 and Node.js v8.11 Here is the console log: Unable to save binary /home/amit/demo/node_modules/node-sass/vendor/linux-x64-57 : { Error: EACCES: permission denied, mkdir ...

What is the best way to display the output of a Set-typed function using a class key in my code?

I'm currently working on developing a function that can return a Set containing the keys of a class. However, I am struggling to determine the correct definition for this function. class Bot { public no01: number; public no02: number; construct ...

Encountered a hiccup during the installation of ssh2-sftp-client on Next.js

I'm looking for a way to save uploaded files in my domain's storage using SFTP. I came across the multer-sftp package, but when I attempted to run the command yarn add multer-sftp ssh2-sftp-client, I encountered a strange error with the second pa ...

Return the reference to an injected service class from the location where it was implemented

Is it feasible to return a reference from a component class with a custom interface implemented to the injected service class in my Angular 6 project? Here is an example of what I am aiming for. ServiceClass @Injectable() export class MyService { co ...

Error: Unable to access the 'registerControl' property of the object due to a type mismatch

I'm struggling to set up new password and confirm password validation in Angular 4. As a novice in Angular, I've attempted various approaches but keep encountering the same error. Seeking guidance on where my mistake lies. Any help in resolving t ...

What is the reason behind the TypeScript HttpClient attempting to interpret a plain text string as JSON data?

When utilizing Angular TypeScript, I have implemented the following approach to send a POST request. This request requires a string parameter and returns a string as the response. sendPostRequest(postData: string): Observable<string> { let header: ...

Undefined error when refreshing Angular page

One particular page on my forum-like website is causing issues with refreshing. In my project, users can log in, view their profiles as well as others'. However, when I refresh a profile page, no data loads from the server and an error appears in the ...

When you use the 'Deploy to Azure' extension in VS Code to deploy your Angular App, the environment.ts settings get updated

While attempting to deploy my Angular App (mysite.com) to Azure using the 'Deploy to Azure' extension in VS Code, I encountered an issue. The api url specified in the environment.ts file (myapi.com) is not being utilized when accessed within the ...

Error message: The property .match cannot be read as it is undefined (AWS Amplify Build Error)

I'm facing an issue when trying to deploy my React/Typescript app using Amazon's AWS Amplify. The build process keeps failing and the error message says: "Cannot read property .match of undefined". I've gone through numerous discussions, bu ...

Is it possible to selectively export certain interfaces within a .d.ts file?

// configuration.d.ts export interface Configuration { MENU_STRUCTURE: Node[]; } interface Node { name: string; } Looking at the snippet above, I am aiming to only export Configuration. However, I noticed that I can also import Node from an ext ...

Using Cypress.Promise in a Cypress command causes type conflicts

When using Cypress 8.x.x, the following Cypress command works fine: declare global { namespace Cypress { interface Chainable<Subject> { login(): Chainable<Token>; } } } Cypress.Commands.add('login', () => { ret ...

Exploring the Contrast in Typescript: Static Members within Classes vs Constants within Namespace

When creating this namespace and class in Typescript, what distinguishes the two? How does memory management vary between them? export namespace TestNamespace { export const Test = 'TEST'; export const TestFunction = (value:string):boolean = ...

Checking for non-falsy variables that include 0 in JavaScript

What is a more graceful method for checking if a variable is truthy but also passes when it's equal to 0? The current verification if(var !== undefined && var !== null) is lengthy and doesn't account for all scenarios such as undefined or ...

issue connecting asynchronous pipe inside a custom directive input

There seems to be a bit of an issue! I have a custom directive that adds a hidden attribute based on input provided. import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core'; @Directive({ selector: '[ticketingPrim ...

In Angular2, the derived class can inherit decorators

Within my Angular application, I am utilizing the BaseComponent which has a specified template. My goal is to use this same template HTML in a component that extends the base one. However, I am aware that class inheritance in Angular2 only applies to cla ...