I have a set of TypeScript functions that are currently scattered across components. These functions are being duplicated unnecessarily, and I am looking for a way to centralize them so all components can access them without redundancies.
Since these functions utilize services like httpClient, what would be the best approach to consolidate them into one centralized location?
Here is my proposed solution using a service:
1. Run the command: ng g s javascript-library
2. Go to app.module.ts and import the service
3. Import { JavascriptLibraryService } from './services/javascript-library.service';
4. Add it to the providers array in app.module.ts:
providers: [
JavascriptLibraryService
],
5. Add the following code to services/javascript-library.service.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class JavascriptLibraryService {
constructor() { }
blp_test(input) {
return 'Hello from Library Service';
}
}
6. Navigate to the component where the function will be used, import the service, and perform dependency injection
(Example in my-component.ts)
6a. Import { JavascriptLibraryService } from './../../services/javascript-library.service';
6b. Perform dependency injection
constructor(
private javascriptLibraryService: JavascriptLibraryService,
) {
}
7. Finally, try to use the function within the component!
ngOnInit(): void {
this.javascriptLibraryService.blp_test(); // Successful execution
}