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

Access a Map URL through a native mapping application on your device

Q: I'm looking to open a specific type of link on the Native Map app. Can anyone recommend a plugin that would work for this scenario? https://www.google.com/maps?q=15405 Hebbe Ln+Au... I tried using the Capacitor Browser plugin and it worked well o ...

Record the variable as star symbols in the VSTS Extension

I am working on a VSTS extension using Typescript and utilizing the vsts-task-lib Currently, I am encountering an issue with the execSync function, which displays the command being executed. However, I need to hide a token obtained from a service by displ ...

What is the proper way to declare app.use using TypeScript with the node.js Express module?

I am working on a node.js app that utilizes typescript with express. In my code, I have defined an error middleware function as shown below: app.use((error:any, req:Request, res:Response, next:NextFunction) => { res.status(500).json({message:error.m ...

Cypress mistakenly looks for cypress.config.js instead of .ts and attempts to find a file in an incorrect directory

Working within a NX mono repo, I am running component tests for an Angular app using Cypress. However, I keep encountering an error in the cypress app that occurs when a test reruns after making changes to the testing code: Your configFile threw an error f ...

Exploring the power of flow.js within an Angular 2 Typescript project

I am trying to incorporate flowjs or ng-flow into my Angular 2 application. After installing the flowjs typings using npm install --save-dev @types/flowjs from However, upon importing it into my component with import { Flow } from 'flowjs';, ...

Angular component.html does not compile due to a check that includes inline array creation

There is an enum called Status: export enum Status { SOME_VAL = "SOME_VAL", SOME_VAL_2 = "SOME_VAL_2", SOME_VAL_3 = "SOME_VAL_3"; } Also, I have an interface named SomeInterface: export SomeInterface { status? ...

Achieving VS Code/typescript autocomplete functionality without the need to import the library

When a module (for example, moment.js, knockout, or big.js) is added with a <script> tag like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"> </script> that defines a global property (for instance ...

Error Message: Angular NullInjectorException - The provider for "[Object]" is not found

While developing a simple Flashcard application that performs CRUD operations using Angular, Node.js, Express, and PostgreSQL, I encountered the following error: flashcards-area.component.ts:24 ERROR NullInjectorError: R3InjectorError(AppModule)[Flashcard ...

Implement conditional props for a React component by linking them to existing props

In my current project, I am working on a component that has a loading state. The component has an isLoading prop which determines whether the component is currently in a loading state or not: interface CustomImageComponentProps { isLoading: boolean ...

What events can cause all store states to be loaded when the page is altered?

I am currently utilizing ngrx/store, ngrx/effects, and ngrx/router. The implementation of my effects is structured as follows: @Effect() loadOneProduct$ = this.updates$ .whenAction(LOAD_ONE_PRODUCT) .switchMap(() => this.productService.loadOn ...

Why is the value always left unused?

I am having an issue with handling value changes on focus and blur events in my input field. Here is the code snippet: <input v-model="totalAmount" @focus="hideSymbol(totalAmount)" @blur="showSymbol(totalAmount)" /> ...

Is there a way to assign values of object properties to the corresponding object in TypeScript?

I'm looking for a solution in TypeScript where I can map values of object keys to the same object, and have IntelliSense work correctly. Here's an example that illustrates what I need: const obj = getByName([ { __name: 'foo', baz: &ap ...

Best practice for importing ts files from an npm package

When faced with the need to divide a ts project into multiple repositories/packages for creating microservices, the challenge arises in combining these packages efficiently. Some packages are required in one microservice, others in another, and some in all ...

Error: The type 'boolean | (() => void)' cannot be assigned to type 'MouseEventHandler<HTMLButtonElement> | undefined'

Playing audio in a NextJS app while writing code in TypeScript has been an interesting challenge. The onClick() function performs well in the development environment, triggered by npm run dev. <button onClick ={toggle}> {playing ? "Pause" : ...

Error: Unexpected character < in node_modules/angular2/ts/package.json syntax

I am currently working on developing an app with Angular 2 and have encountered an error during setup. The error message I received is: SyntaxError: /home/mts/Desktop/sampleProject/appSails/node_modules/angular2/ts/package.json: Unexpected token < at O ...

gulp-tsc cannot locate the src directory

I am currently working on developing a .NET Core application using Angular2, but I keep encountering the following error: /wwwroot/NodeLib/gulp-tsc/src/compiler.ts' not found. I'm having trouble pinpointing what I might be missing. tsconfig.js ...

Compiling TypeScript files with an incorrect path when importing, appending "index" at the end of the @angular/material library

I'm currently working on creating a library to collect and distribute a series of Angular components across various projects, with a dependency on angular/material2. My objective is to eventually publish it on npm. However, I've encountered an i ...

Issue with triggering angular function multiple times in certain conditions

Issue: Experiencing difficulties with Angular directive as it is being called multiple times, resulting in incorrect transaction outcomes and multiple entries on the Console screen. Desired Outcome: Ensure that the function executes only once. Sample cod ...

No interface 'JSX.IntrinsicElements' could be found, causing the JSX element to be implicitly of type 'any'

<Header> <title>Real Estate API Application</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, ...

The NgRx Store encountered an error: Unable to freeze

I am currently developing a basic login application using Angular, NgRx Store, and Firebase. I have implemented a login action that is supposed to log in to Firebase and store the credentials in the store. However, it seems like there is an issue in my imp ...