#Inheritance of classes in Angular

19 messages · Page 1 of 1 (latest)

tardy raft
#

I want to create a class to work with the data that the component will give me. I came to the conclusion that I want to create a base class, and several children in which there will be some functionality, how to implement it correctly in Angular and where to put these classes.

muted ingot
#

Why that conclusion?

tardy raft
# muted ingot Why that conclusion?

Perhaps this can be done through services, but in this case, how do I implement inheritance of methods and properties. But I think the service does not imply inheritance

#

So I decided what can be done through regular classes

muted ingot
#

A service is just a class with a decorator.

tardy raft
#

can I just move my these classes to the utils folder?

muted ingot
#

Probably, but I am not sure what u are trying to achieve.

tardy raft
#

I want to find out if I can safely use inheritance or if Angular does not recommend using this mechanism and there is another method

silk swan
#

I decided to try it in the last app I worked on.

We had about 20 different entities that were very similar. They all needed basic CRUD operations. They all used a mat-table to display with server side filtering, pagination & sorting. So the abstract class I made also included a generic service that would take the entity type. It worked out well. Some entities needed to have more logic when saving or loading. I could just override that method in the extended class.

I'm not sure if there is a better approach to this. But it worked for me in this case. I'd love to hear other techniques.

muted ingot
#

You can either use inheritance, or composition.

#

Googleing on those two will show you there are two kinds of people, one prefers inheritance, the other composition.

#

I believe composition is the better idea.

#

So u move the shared stuff in a seperate class that u use in the others, instead of in the base.

#

and instead of doing this.someBaseMethod, you use this.someService.someMethod.

#

Both work, but inheritance doesnt scale when u need to use multiple, unrelated, shared, functionality.

#

Composition does scale, and u can inject two classes and use them, rather than fill the base with all the stuff, or inherit twice.

waxen lantern
#

This question about classes and inheritance doesn't relate to Angular.

#

If you're talking about a component extending or implementing another class, then yes.
You can just make a base class or base component and then go for it

#

But remember, generally,
Making too many abstractions will result in a base class which ends up having redundant methods and fields.

Make sure your base classes, have purpose only for what they are needed.