Angular constructor replication

I am facing a dilemma with 4 components, all of which have the same constructor. As a beginner, I am unsure how to approach this problem differently. Should I consider creating a service that encompasses what I refer to as common elements?

What would be your recommendation on how to handle this situation effectively?

The current constructor code used across all 4 components is as follows:

constructor(private transverseService: TransverseService, private webReferentielService: WebReferentielService) {

        this.transverseService.setLanguage(new Messages(this.webReferentielService));
        this.messages = this.transverseService.getMessages();

        transverseService.messageObservable.subscribe(
            msg => {
                this.messages = msg;
            }
        );

        this.transverseService.initConfig().then(data => {
            this.configEnv = data;
            this.version = this.configEnv.version;
            this.env = this.configEnv.env;
        });

    }

Answer №1

To tackle this, you have the option of developing a singleton service,

@Injectable({providedIn: 'root'}) 
export class SomeService{

        // include variable declarations here
   
        constructor(private transverseService: TransverseService, 
                    private webReferentielService: WebReferentielService, 
                    /** insert other dependencies */) {

        this.transverseService.setLanguage(new Messages(this.webReferentielService));
        this.messages = this.transverseService.getMessages();


        transverseService.messageObservable.subscribe(
            msg => {
                this.messages = msg;
            }
        );

        this.transverseService.initConfig().then(data => {
            this.configEnv = data;
            this.version = this.configEnv.version;
            this.env = this.configEnv.env;
        });

    }  
}

When it comes to components(s),

    constructor(private someService: SomeService){
         // utilize someService here
    }

Answer №2

To create a common base for your 4 components, you can utilize an abstract class that they will all extend.

export class AbstractComponent {
  constructor(
    protected transverseService: TransverseService,
    protected webReferentielService: WebReferentielService
  ) {
    // any necessary initialization logic can go here
    // ...
  }
}

Your individual components would then be structured like this:

@Component({
  selector: 'component-1',
  ...
})
export class ComponentOne extends AbstractComponent {
  // inherits the constructor from the abstract class
}


@Component({
  selector: 'component-2',
  ...
})
export class ComponentTwo extends AbstractComponent {
  // also inherits the constructor from the abstract class
}

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

Using Angular2 to import components and services from a module

I am currently developing a final Angular2 application with two modules: CoreModule: This module includes shared components and services. AppModule: The main module of the application. AppModule: /** * Created by jamdahl on 9/21/16. */ // Imports impo ...

I am looking to use Angular Material to perform a calculation on two mat-cell input values and display the result in a separate mat-cell within dynamically added columns

A mat-table has been created with dynamically added columns. The goal is to perform an operation in two columns (Unit Price * Qty/Rolls) and display the results in the Amount column. In the footer, the total Qty/Rolls and amount should be shown. Here' ...

Sort out the information in the table

Seeking assistance on how to filter a table based on certain conditions. Refer to the sample image provided in the link below: https://i.sstatic.net/Egvj6.png Here is the code I have attempted: this.reportData.filter(it => { if ( ...

Looping Through RxJS to Generate Observables

I am facing the challenge of creating Observables in a loop and waiting for all of them to be finished. for (let slaveslot of this.fromBusDeletedSlaveslots) { this.patchSlave({ Id: slaveslot.Id, ...

"Implementing self-referencing mongoose models in Typescript: A step-by-step guide

I have a model: const message = new mongoose.Schema({ id: { type: ObjectId, required: true }, text: { type: String }, replies: [message] }); Looking to create a document structure like this: { "id": 1, "text": "Main Message", "replies": [ ...

Ways to decrease the space between lines of text within a single mat-option element

https://i.sstatic.net/Sr1cb.png ::ng-deep .mat-select-panel mat-option.mat-option { height: unset; } ::ng-deep .mat-option-text.mat-option-text { white-space: normal; } Currently, I have implemented this code to ensure that text in options wraps to t ...

What is the method for adding local images to FormData in Expo version 48 and above?

When working with Expo v47 and its corresponding React Native and TypeScript versions, FormData.append had the following typing: FormData.append(name: string, value: any): void An example of appending images using this code could be: const image = { uri ...

Angular is throwing an error due to an unexpected token when running on an IIS server within a subfolder

I have recently developed an Angular 11 template (Angular version 11 + .Net core 5.0) using visual studio 2019. The Angular application needs to be accessed from a subfolder called caui rather than the root folder. After publishing the Angular application ...

Running out of memory due to inefficient mark-compacting processes nearing the heap limit in Angular 8 allocation

A significant portion of the modules are built, with only one active in progress. The process is located at ...\src\index.js??extracted!D:\Clients\app\node_modules\sass-loader\lib\loader.js??ref--15-3!D:\src&bso ...

Reduced number of node modules

Which node modules are essential for a basic project? Is it possible to manually remove unnecessary ones or should I use npm install [a few essential requirements] I have a small website consisting of 5-10 pages where only one makes http requests to serv ...

How can I display a div within a parent container in Angular 2?

Instead of pasting my loading modal pop-up to every page in the app, I want it to appear at the parent component (i.e. "app.component.ts"). This way, I can easily call it multiple times throughout the application. Now, I have pages with different routes t ...

The confirmPasswordReset function in Angularfire auth is not defined in the User type

I am currently working on integrating password reset functionality using the angularfire2/auth class, following the steps outlined in this guide: https://medium.com/@c_innovative/implementing-password-reset-can-be-a-tricky-but-inevitable-task-737badfb7bab ...

A mistake was made: The template contains errors stating that 'app-my-profile' is an unknown element

I encountered an error message: "Uncaught Error: Template parse errors: 'app-my-profile' is not a known element," while working on setting up my profile service. import { BrowserModule } from '@angular/platform-browser'; import { NgM ...

Converting input tag to a method in component with uppercase transformation

Currently, this code resides within the <input tag I am looking to convert this code into a method in my component. Any ideas on how to do this? oninput="let p=this.selectionStart; this.value=this.value.toUpperCase(); this.setSelectionRange(p,p) ...

How to halt the ng-serve process

Can you assist me in finding a script that can stop this issue on both Windows and Mac operating systems? ...

The argument supplied in Angular using TypeScript is incompatible: a 'string' type cannot be assigned to a parameter expecting an 'Element' type

I'm facing 3 errors with Typescript in angular when working with D3js elements. I tried to create a mouseover event to display tag and value data corresponding to the bar graph, but encountered issues. I attempted declaring strings and even added "noI ...

TS2304: The build process is unable to locate the name 'iterable' within @types

As an experienced dog attempting to master new tricks like npm and TypeScript, I find myself faced with a challenge in my Visual Studio 2017 project. Despite setting it to "Latest" TypeScript 2.5 and adding @types/jquery (3.2.12), the project keeps throwin ...

What can I do to enhance the efficiency of this function in React?

Issue I am facing a problem with two inputs that trigger an event to update the quantity of a specific product. However, I noticed that entering a number quickly tends to slow down the process, especially when dealing with multiple products. It takes abo ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...

Angular attribute directive encountered an error during production build, where it was expected to receive 1 argument but instead received

I have been working on a large-scale application that has been developed by multiple teams over an extended period. A frontend developer from another location included a significant amount of repetitive imperative code, utilizing jQuery for DOM manipulati ...