Is it considered best practice to pass an argument that represents an injectable service?

Is it a good practice to pass an argument that is an injectable service to a function?

Hello everyone, I have been doing some research but have not found a definitive answer to the question above yet. I am currently working with Angular and came across some code that has left me confused about what practice to follow or avoid.

Scenario:

shopping-util.ts

export class ShoppingUtil {

    public static buildShopingNote(material, bService: BService) {
        if (!material) {
            return '';
        }
        return bService.doSomeThing(material);
    }
}

b-service.ts

@Injectable()
export class BService {
    public doSomeThing(input): string {
        let result = 'do something with input';
        return result;
    }
}

I am wondering if we should move the function 'buildShopingNote' to a business service instead so that we can inject the BService when the service is initialized? And would the same answer apply for other programming languages (Java, C ..) as well, in your opinion?

Any ideas are appreciated!

Answer №1

When utilizing the bService multiple times, it becomes evident that relocating the service to the constructor of the class is the best course of action. Nonetheless, if the service is only needed once, there are various approaches you can take. In the existing code, there is no need to create the ShoppingUtil class since constructing it is unnecessary when it solely contains static functions. You have the option to either establish a namespace or directly export a function from the Util. Another possibility is to transfer buildShopingNote to the BService

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing mapped types in a proxy solution

As I was going through the TS Handbook, I stumbled upon mapped types where there's a code snippet demonstrating how to wrap an object property into a proxy. type Proxy<T> = { get(): T; set(value: T): void; } type Proxify<T> = { ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

Errors with the email composer in Ionic 3 displaying "plugin_not_installed" issue

Currently utilizing this feature within my Ionic 3 application. The plugin has been successfully installed, and the cordova-plugin-email-composer folder is present in the plugins directory. Despite multiple attempts of uninstalling and reinstalling, an err ...

Error: Gulp is using ts-node and returning 'void' instead of 'Task', but it cannot find the type 'Task'

Seeking assistance from experienced individuals in the realm of gulp.js and typescript - could someone provide guidance for a struggling newcomer? I am currently utilizing the most recent versions of all relevant tools (node, ts-node, gulp, ts, @types/gul ...

While using Angular CLI on GitLab CI, an error occurred indicating that the custom rule directory "codelyzer" could not be

ng lint is throwing an error on Gitlab CI stating: An unhandled exception occurred: Failed to load /builds/trade-up/trade-up/common/projects/trade-up-common/tslint.json: Could not find custom rule directory: codelyzer. The strange thing is that ng lint ru ...

Exploring the Impact of 2 HostBindings on Class Generation from Inputs in Angular 4

I'm struggling with the code in my component, which looks like this: @Component({ selector: "home", templateUrl: "./home.html" }) export class Home { constructor() {} @HostBinding("class") @Input() public type: string = "alert" @HostBindi ...

Navigate to a new page on button click using Row with Tanstack / React-Table and Typescript (2339)

Encountering a linting error when attempting to navigate to a new route by clicking on a table row. The functionality is working but how can I resolve this issue? It's showing an error message stating "The property "id" for type TData does not exist." ...

Storing a variable in Cypress with Typescript for use in the afterEach teardown step

Throughout my test cases, I store data in a variable to be used consistently. The variable maintains its value until the very end of the test, but when trying to access it in the @afterEach teardown function for global clean up, it appears empty. It seems ...

Exploring the depths of TypeScript's intricate type validation

Could you please review the comments in the code? I am trying to determine if it is feasible to achieve what I need or if TypeScript does not support such functionality. I require type checks for my addToRegistry function. Play around with TypeScript in ...

What is the validity of using Promise.reject().catch(() => 5) in Typescript?

Can you explain why the TS compiler is not flagging an error for this specific code snippet? Promise.reject().catch(() => 5) Upon inspecting the definition of the handler function within the catch, we come across the following code: interface Promise&l ...

Encountering difficulty in reaching the /login endpoint with TypeScript in Express framework

I'm currently working on a demo project using TypeScript and Express, but I've hit a roadblock that I can't seem to figure out. For this project, I've been following a tutorial series from this blog. However, after completing two parts ...

Issue: The element '[object Object]' is of type 'object', which is not supported by NgFor. NgFor only works with Iterables like Arrays. - Problem encountered in an Ionic Project

I'm currently working on retrieving my user's username from Firebase Firestore Database using Ionic and AngularFire. I have implemented the valueChanges() method to obtain the observable and am trying to process it using an async pipe. However, u ...

Typescript enables bidirectional control of Swiper

I attempted to use the two-way control slider example from Swiper documentation, but I encountered TypeScript errors that prevented it from working correctly. Is there a way to make it compatible with TypeScript? The specific errors I received were: TS23 ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...

Angular Karma Error - MatDialogRef Provider Not Found

While testing with Angular Karma, I encountered the following error... NullInjectorError: StaticInjectorError(DynamicTestModule)[ManageProblemsComponent -> MatDialogRef]: StaticInjectorError(Platform: core)[ManageProblemsComponent -> MatDialogRef]: ...

Limiting the character input in ion-textarea within Ionic 2: A step-by-step guide

In my Ionic 2 application, I need to limit user comments to less than 500 characters in a text area. What is the best way to implement this restriction? ...

The assignment of Type Program[] to a string[] is not valid

I am working with a class that contains information about different programs. My goal is to filter out the active and inactive programs, and then retrieve the names of those programs as an array of strings. Below is the structure of the Program class: ex ...

What is the reason for TS expressing dissatisfaction about the use of a type instead of a type entry being provided

Below is a snippet of code for a Vue3 component that takes in an Array of Objects as a prop: <script lang="ts"> interface CorveesI { What: string, Who: string, Debit: number } export default { name: 'Corvees', props: { ...

I encountered a roadblock with my Npm start process when it got stuck at 70% completion after incorporating the "lazy

I have encountered a problem that has previously been discussed here, but none of the solutions seem to work for me. I recently incorporated this module into an existing project: import { NgModule } from '@angular/core'; import { CommonModule } ...

The tsconfig within the module directory fails to supersede the extended tsconfig properties present in the parent directory

Within the directory store/aisle/fruits, there is a tsconfig.json file: { "compileOnSave": true, "compilerOptions": { . . "target": "es6", "noEmitOnError" : true, "noEmitHelpers ...