In my C# backend I have classes for my entities and entity lists. When I need a function/method on that entity or entity list, I just add it to the class.
In Angular/TypeScript models are defined as interfaces in every example I come across. How should I organize the functions that operate on objects of these interfaces?
I'm using NgRx, and it is tempting to put much of this code alongside the selectors, but I feel that it will quickly become quite messy.
CodePudding user response:
The same rules apply as in C#. The models don't have to be interfaces, they can also be a class if they need to include functionality.
For example,
export class Person {
firstName: string;
lastName: string
get fullName(): string {
return `${firstName} ${lastName}`;
}
}
However, since you're using NgRx, it's recommended to not store objects like this in the store - that's why most use interfaces.
In that case, I would create a new "selectors" file, and store the logic there to retrieve the full name. Easy to test your business logic there as well.
CodePudding user response:
You can use classes and the class keyword in Angular/typescript/(modern) javascript. A rule of thumb is to use an interface to store data (like DTO/POCO s in c#) and if you are modeling behavior use a class.
Furthermore, if you want to separate the logic, you should use delegate that to services, just like in server side frameworks like .net and spring.
A good place to start is John Pappa's angular style guide. github.com/johnpapa/angular-styleguide . This has has been the de facto place to see best practices for a while now. Good luck!