When it comes to utilizing a service, here's a condensed example from one of the applications I've worked on:
import {Injectable} from '@angular/core';
import * as _ from 'lodash';
@Injectable({
providedIn: 'root' // If you're not using Angular v6+, just use @Injectable()
})
export class UtilsService {
findObjectIndex(list: any[], obj: any, key: string): number {
return _.findIndex(list, function(item) {
return obj[key] === item[key];
});
}
findObjectByQuery(list: any[], key: string, query: string): any {
return _.find(list, function(item) {
return item[key].toLowerCase() === query.toLowerCase();
});
}
}
By injecting this service, you can easily apply it in various components and maintain consistency.
To inject the service, you simply include it like this:
import {UtilsService} from 'app/shared';
export MyComponent {
constructor(private utils: UtilsService) {
utils.findObjectIndex([], {}, 'id'); // This is just an example
}
}
NOTE:
While static functions are an option, I personally steer clear from them due to testing challenges and limitations when it comes to injecting dependencies later on. Static functions cannot utilize injected elements, causing headaches during future modifications.
Avoid falling into the same trap I did, as it may lead to rewriting substantial portions of your codebase.
UPDATE 2:
Another approach involves utilizing regular functions for scenarios where dependency injections are not needed, typically seen with simple helper functions. Create a file such as helpers.ts
(or multiple files if there are several functions) and implement the following:
export function sum(a: number, b: number) {
return a + b;
}
Alternatively, you can use this syntax:
export sum(a: number, b: number) => {
return a + b;
}
You can now import these functions with the following statements (based on whether all functions are in a single file or split across multiple files):
import { sum } from 'helpers';
import { sum } from 'helpers/sum';
This method offers easy tree-shaking capabilities and simplifies unit testing compared to using a service, as no extra steps are necessary to get the service functioning in tests.