What is the process for assigning custom constructor parameters to an Angular Service during its creation in an Angular Component?

I have been tasked with converting a Typescript class into an Angular 6 service:

export class TestClass {
    customParam1;
    customParam2;

    constructor(customParam1, custom1Param2) {
        this.customParam1 = customParam1;
        this.customParam2 = customParam2;
    }
} 

This is the new service:

@Injectable({
  providedIn: 'root'
})
export class TestClassService {
    customParam1;
    customParam2;

    constructor(customParam1, custom1Param2) {
        this.customParam1 = customParam1;
        this.customParam2 = customParam2;
    }
} 

When creating the initial code block in Angular, you would use new TestClass("one", "two").

How can I set customParam1 and customParam2 when creating an instance of the TestClassService in a component?

Answer №1

If you were unaware,

constructor(parameter1, parameter2) {
    this.parameter1 = parameter1;
    this.parameter2 = parameter2;
}

Represents the expanded version of

constructor(private parameter1, private parameter2) {}

Now, onto your inquiry : when you offer your service at the root level, it will generate a singleton : since services serve as dependencies for other functionalities (like components), they will be initialized first (or their instance will be passed on, but the end outcome remains the same).

If you wish to assign values to your service, you need to utilize setters : whether they are methods or actual setter functions.

setParameter1(value) { this.parameter1 = value; }
set setParameter2(value) { this.parameter2 = value; }

this.setParameter1('your value');
this.setParameter2 = 'your value';

Alternatively, you would need to create a new instance of your service, but that would go against the singleton concept.

It would be most beneficial for you to explain your objective, so we can determine the most suitable solution for you.

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

Menu selection that changes dynamically based on radio button selection

Currently, I have four radio buttons and my goal is to have a drop-down menu change based on the selected radio button. Should I pre-write all the drop-down options and display them accordingly, or would it be better to use ajax to fetch the values from th ...

JavaScript tool for connecting tags with JSON properties

As a beginner in JS, I am curious if there exists a JS library that can help bind html fields to a JS object. For example: <div class="js_source"> <input field="name" /> <input field="surname" /> <button type="button">S ...

Maximizing the power of datatables with ajax integration

Exploring pagination with AJAX on datatables.net is something I want to try. I have two input fields where users can enter start and end dates, followed by the table structure below: <table class="table table-hover" id="example"> < ...

Re-rendering components using arrow functions

Using an arrow function, I have implemented a feature to toggle a div and show/hide a button based on the div's visibility. toggleDeliveryDiv = () => { document.getElementById('btn_collapse_delivery').click(); this.s ...

Encountering a getStaticProps error while using Typescript with Next.js

I encountered an issue with the following code snippet: export const getStaticProps: GetStaticProps<HomeProps> = async () => { const firstCategory = 0; const { data }: AxiosResponse<MenuItem[]> = await axios.post( ...

Error message: Typescript class unable to access methods because of undefined properties (TypeError: Cannot read properties of undefined (reading 'method_name'))

During the compilation process, everything goes smoothly with no errors. However, when I try to call the method in the controller, an error occurs. It seems that some class methods are missing during the compilation phase. If you require more information ...

Newbie: Troubleshooting Vue Errors - "Vue is not recognized"

I'm currently at the beginning stages of learning Vue and am practicing implementing it. However, I keep encountering the errors "vue was used before it was defined" and "Vue is not defined". Below are excerpts from my HTML and JS files for reference. ...

Difficulty Encountered in Rendering Component Using setTimeout Function

Having trouble figuring out why my component, enclosed in a setTimeout function, is not appearing on the DOM: const ContentMain = Component({ getInitialState() { return {rendered: false}; }, componentDidMount() { this.setStat ...

What could be causing my Puppeteer scraper to malfunction when I alter the search term?

The Task In this project, I am building a web scraper using NodeJS with Puppeteer. The goal is to scrape data for "Jeep Wranglers" and organize the results in JSON format. Comparing IPhone X and Jeep Wrangler Initially, everything worked smooth ...

Tips for wiping clean and restarting data in a modal?

After closing and reopening this modal, both the old information and new data remain. I aim to reset everything within the modal, wiping out details from both the header and body. Expected scenario - https://i.sstatic.net/Z42Rk.png Actual situation - http ...

Developing a system mode called "night mode"

I've decided to incorporate a dark mode feature into my Wordpress theme. Creating both dark and light modes was a breeze, but now I want to add a third mode that serves as the default for pages. This new mode will automatically switch between dark a ...

Troubleshooting issues with Angular Material's basic mat-autocomplete functionality

After spending more than 72 hours trying to resolve this issue, I have hit a roadblock. Oddly enough, when I create a minimal working example in stackblitz, everything functions perfectly. The problem lies within a simple mat-autocomplete embedded within ...

Utilizing React to highlight buttons that share the same index value upon hover

I have some data in a JavaScript object from a JSON file, where certain entries have a spanid (number) while others do not. I've written React code to highlight buttons with a spanid on hover, but I'm looking for a way to highlight or change the ...

Transform a string (variable) into an object using JSON.parse, encountering an unexpected token error

I am struggling with parsing a string variable back to an object. Despite searching through various posts on this issue, I have not found a solution that works for me. if(subMatch.match(/\{.*\}/)){ /// new Object of some sort var o ...

Preserving the background image on an html canvas along with the drawing on the canvas

Can users save both their drawings and the background image after completing them? var canvas = document.getElementById("canvas"); // This element is from the HTML var context = canvas.getContext("2d"); // Retrieve the canvas context canvas.style.ba ...

The changing perspective in relation to the current position of a background

I am currently working on implementing a parallax effect, which is mostly successful. However, I have encountered a minor issue. Instead of the parallax effect being relative to the element's current position, it abruptly jumps to position 0. How can ...

When using Angular and Express together, the session is not continuous as each new request generates a fresh session

Unique Question I have encountered an issue with passport.js while trying to implement authentication in my express application. When I use req.flash('message', 'message content') within a passport strategy, the flashed information see ...

The basic function is ineffective when used within an if-condition

I am currently dealing with a JSON file that has some nesting: { "name": "1370", "children": [ { "name": "Position X", "value": -1 }, {...} ] "matches": [ { "certainty": 100, "match": { "name": "1370 ...

Using Jquery and CSS to display or conceal table elements depending on viewport width

I am seeking advice for my issue. Here is the code snippet on JSFiddle. I have a list of models and corresponding values that vary across different categories. I have created a simple table to display this data. However, I need to alter the table structur ...

What is the best way to determine if an object is empty?

I have an array object that I need to check for emptiness. const sampleData = { test:[], test2:[], test1:["can"] } This is the code I'm using to check for emptiness: const dataObject = Object.values(sampleData) console.log(d ...