Using Angular: Passing a service as a parameter

I have a desire to improve the organization of my code by moving certain functions into an external file and accessing them from multiple components.

These functions rely on a service:

The MyFunctions Class

import { Service1 } from "../_services";
export class MyFunctions {
  constructor(private service: Service1) {}
  bookingFunctions = {
    confirm: (id: any) => {
      this.service.confirmTrip(id);
    }
  };
}

My Component Implementation

import MyFunctions from "../../../functions";
...
export class AppComponent {
  constructor(
    private service: Service1
    ) {}
...
    myFunctions = new MyFunctions(this.service);
... 
    confirmBooking(id: number){
      this.myFunctions.bookingFunctions.confirmBooking(id);
    }
... 
}

After successfully implementing this setup, I am curious as to why it is not more commonly used. Are there any drawbacks to this approach?

Is it acceptable to pass the service instance Service1 to the constructor of the MyFunctions class?

I find myself wondering, "It works! But how?"

Answer №1

It is possible that within your 'Service1' service, you have the following code:

@Injectable({ providedIn: 'root' })

This means that the service instance will be shared across the entire application, similar to a singleton.

If you do not include providedIn: 'root', and instead inject the service into the PROVIDERS:[] section of a module, the service will only work within that specific module.

Alternatively, if you define the service within a component like this:

// Component A

@Component({
/* . . . */
  providers: [MyService]
})

The service will only be available to that component and its descendants, not to other components. If another component also declares the same service in a similar manner:

// Component B

@Component({
/* . . . */
  providers: [MyService]
})

both components will not share the same service; they will each have their own separate instances of the service.

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

What is the best way to effectively handle the proxying of objects across multiple levels?

As illustrated in a Stack Overflow thread, utilizing Proxy objects is an effective method for monitoring changes in an object. But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects. I am curren ...

Determine the specific cell involved in an HTML5 drag-and-drop interaction within a table

I've been experimenting with the HTML5 drag and drop functionality in an Angular project. Here's the setup I'm working with: A container containing draggable 'objects' A table where users can drop the dragged elements Following ...

Transforming an array of elements into an object holding those elements

I really want to accomplish something similar to this: type Bar = { title: string; data: any; } const myBars: Bar[] = [ { title: "goodbye", data: 2, }, { title: "universe", data: "foo" } ]; funct ...

The custom FontAwesome icon is failing to display properly

UPDATE : Here is the StackBlitz as requested. A custom SVG icon was created based on instructions provided by FontAwesome's collaborator found here. Despite mirroring the exact element structure of FontAwesome's icons, the custom icon does not ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...

execute the function once the filereader has completed reading the files

submitTCtoDB(updateTagForm:any){ for(let i=0;i<this.selectedFileList.length;i++){ let file=this.selectedFileList[i]; this.readFile(file, function(selectedFileList) { this.submitTC(updateTagForm,selectedFileList); }); } } } ...

Execute various Office Scripts functions within a single script based on the button that is selected

Imagine you have an Excel spreadsheet with two buttons named populate-current and populate-all. Both buttons execute the same Office Script function that looks something like this: function populateByRowIndex(workbook: ExcelScript.Workbook, rowIndex: numbe ...

The Angular SSR feature is throwing errors due to non-ESM modules present in my Express API implementation

In my Angular SSR project, I have set up my Express API to run as part of the SSR service. The app code is located in /src/app, while the API code resides in /src/api. There are some imports of the API code into the app code, primarily for using the same t ...

How can we remove a dynamic component in Angular?

Here is the HTML template for a modal component: <div class="modal"> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"> <button (click)=&q ...

Double curly brace Angular expressions being repeatedly evaluated during mouse click events

Within our Angular application, the code structure is as follows: <div>{{ aGetProperty }}</div> <div>{{ aMethod() }}</div> Upon clicking anywhere on the page, these expressions are being evaluated repeatedly. For example, if there ...

Issue with the loss of scope in the Subscribe event causing the Clipboard Copy Event

Hey there, currently I am attempting to implement a text copying feature in Angular 2. I have a function that executes when a button is pressed, fetching data from the database and converting it into readable text, which is then automatically copied to the ...

When performing an arithmetic operation, the right operand must be a data type of 'any', 'number', 'bigint', or an enumeration type

My JavaScript code needs to be converted to TypeScript for proper functionality. categoryAxis.renderer.labels.template.adapter.add("dy", function(dy, target) { if (target.dataItem && target.dataItem.index % 2 === 0) { return dy + 25; } ...

Troubleshooting TypeScript compatibility with SystemJS when encountering problems with the .js extension

Initializing my TypeScript file with the import statement below. It's important to note that the lack of a .ts extension indicates that I am importing a TypeScript module: import githubService from './github.service'; Through transpilation ...

What is the reason for storing a base64 string as an Object in a MongoDB database?

I am facing an issue with storing a product detail on the mongoDB database. When I try to save it, mongoDB stores a property imageSrc as an object instead of a string. Here is my database This is my angular service And this is my express server request ...

Value in Hook not updating after memoization of parent component

Let's consider this scenario: import * as React from "react"; const useMyHook = ({ element }: { element: HTMLElement | null }) => { React.useEffect(() => { if (element) { console.log("element in hook", element); ...

Fetching all data from a SQLite database in a Listview using React Native

I have been utilizing the library found at https://github.com/andpor/react-native-sqlite-storage in my react native project. To retrieve a single row from the database, I use the following code: db.transaction((tx) => { tx.executeSql('SEL ...

Encountering issues with Angular 4 routing functionality in production environment

Everything seems to be functioning well with the routing in my Angular 4 web-app on my development setup, and the menu redirections are working smoothly in the live version. However, I have encountered an issue where the development version redirects to d ...

Passing Imported Module to Feature Module in Angular 7

In my Angular 7 app, I have set up a hierarchy of feature modules. The structure looks like this: app admin (UI module imported here) feature1 feature2 public Within the admin module, I have included a UI framework module. My question is, if modules ...

Creating a variety of themes with unique color palettes for Angular Material along with custom-designed components

One of the goals for my app is to have multiple themes, including Angular Material themes, with the ability to define custom colors for specific components and elements that are not part of Angular Material. It's important that when I change a theme, ...

Utilize Nativescript XML template for code reusability without the need for Angular

After completing my Nativescript application, I was tasked with incorporating the Telerik-UI "RadSideDrawer". Upon reviewing the documentation, I realized that a substantial amount of XML code needs to be implemented on every page. I am utilizing Typescr ...