Classes and objects in Angular

50 Views Asked by At

Is there any problem with using conventional classes and objects in the code while using Angular?

For example, sometimes, when I'm refactoring and I want to separate a specific logic that is mixed up in a messy code I do something like...

logic-handler.ts

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

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

...and I instantiate an object of this class to handle this certain logic, within the component.ts file.

The problem is that there was a senior on my team who always said he didn't like this idea because he didn't know how Angular deals with new LogicHandler();.

So, is there a real reason to worry about this?

I hope someone can answer my question or provide a better solution to the problem presented.

The fact is that doing it the way I propose is simpler and easier to test.

2

There are 2 best solutions below

0
ghybs On

As implied by @browsermator in the question comments, there is absolutely no issue using normal classes for other uses than for Angular components.

Your app code is normal TypeScript (and JavaScript) code, so classes are supported.

What Angular does, during its AOT phase, is to pick-up all classes decorated with @Component, wrap them (e.g. to link with template and style), and handle all the instantiation during runtime (new...). Same for services and modules.

Therefore, as long as you do not decorate your normal classes with Angular stuff, Angular leaves them alone, and you can use them as in non-Angular world.

BTW there is a high chance you already use such normal class instantiation, typically with new Date() (even if through libraries like date-fns and the like), which proves that there is no compatibility issue with Angular.

0
Samir Ribeiro On

Researching more on the topic, I was able to see that the only problem with this approach is that I am creating a dependency between my component and the LogicHandler.

So, if I need to test my component, for example, I won't be able to mock this object easily, because the dependency is inside the component, and not injected into it. Therefore, it does not respect SOLID's dependency inversion principle (DIP).

Therefore, the correct option in this case would be to create the LogicHandler as a service, and inject it into my component via the constructor.

In short, it is a matter of principle to never instantiate an object within another class directly, precisely because an object should never be responsible for its dependencies.