#Inheritance of classes in Angular
19 messages · Page 1 of 1 (latest)
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
A service is just a class with a decorator.
can I just move my these classes to the utils folder?
Probably, but I am not sure what u are trying to achieve.
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
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.
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.
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.