What is the importance of a subclass providing services to a superclass in Angular?

While exploring some Angular code today, I stumbled upon this interesting snippet:

export class ContentFormComponent extends FormBase {

...

constructor(
  private authService: AuthService,
  private apiService: ApiService,
  private segmentService: SegmentService
) { super(authService, segmentService) }

...

}

The declaration of the superclass FormBaseComponent is as follows:

export abstract class FormBase {

...

constructor (
   protected authService: AuthService,
   protected segmentService: SegmentService
) { }

...

}

I'm curious why this abstract class requires services from its subclasses. In Angular, services are Singleton, meaning there's only one instance throughout the app and both services are provided at root level. So, why doesn't the FormBase class simply inject these services through DI in the constructor definition? Isn't it redundant?

This question may seem basic, but I'm a newbie and eager to learn more about Angular. Your guidance would be greatly appreciated!

Answer №1

To find the answer to your question, please see Dai's comment.

It's important to note that constructors function differently when a class is subclassed. The subclass takes control of the superclass' constructor and all dependencies must now go through the subclass.

In my response, I propose an alternative approach that eliminates the need to pass services to the parent. This method is available starting from Angular 14.

With this new approach, you can move service injection outside of the constructor using the inject function. As a result, subclasses no longer need to worry about passing these services.

export abstract class FormBase {
  protected authService: AuthService = inject(AuthService);
  protected segmentService: SegmentService = inject(SegmentService);
}

export class ContentFormComponent extends FormBase {
  constructor(
    private apiService: ApiService
  ) { super(); }
}

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

Issue encountered with Angular Material's md-chips and md-autocomplete: The error message "control.registerOnChange is not a

When attempting to wrap mat-chips and mat-autocomplete into a ControlValueAccessor, I encountered the following errors: InfoEditorComponent.html:17 ERROR TypeError: control.registerOnChange is not a function at setUpModelChangePipeline (forms.js:2701) ...

Using a specific type of keys, attempting to set two instances of those keys simultaneously will result in an error of that type

Consider this scenario: type Example = { x: string, y: number } const a: Example = { x: "x", y: 1 } const b: Example = { x: "y", y: 2 } const issue = (keys: (keyof Example)[]) => { keys.forEach(key => { a[key] ...

What is the process for adding submitted data to an already-existing local JSON file?

I have a new Angular assignment that requires me to push form data into an existing JSON file locally. The task is to develop an Angular application where users can create new tasks and view them on a separate page. Initially, I attempted using http.post ...

How do I determine if a child component is in a dirty state within CanDeactivateGuard when dealing with multiple form tags?

Currently, I am utilizing a template driven form within my project. The parent component that I am working on is as follows: parent.component.html <tab> <form> <input></input> <button></button> </form ...

Ways to create a fixed button positioned statically at the bottom of a page

Currently, I am utilizing tailwind CSS to create a webpage with Next and Back buttons for navigation. However, an issue arises when there is minimal content on the page as the button adheres to the top. For visual reference, please view the image linked be ...

Exploring the capabilities of automation testing with charts.js and the latest version of Angular

While working on my testing automation for charts.js, I utilized the ngContext object to retrieve data with this code snippet: document.getElementsByTagName('chart-dataset')[0].__ngContext__. However, since upgrading to angular 14, it seems that ...

What causes the "Error: method not allowed" message to appear when attempting to send a "DELETE" request from a Next Js component? (The POST method is

This is my first time on this platform, and I'm currently following a tutorial from Javascript Mastery to create a clone of a thread application. After watching the entire video and building the basic functionality based on it, I decided to enhance th ...

Using Angular 7 to set the value of an object returned by an observable to a variable

I encountered an issue while trying to assign the return value from a service to a component. ngOnInit() { this.getInspectionData(); } getInspectionData() { this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`) ...

Get the date string formatted for an Angular2 date range picker

In my Angular2/Spring web application, I am utilizing a calendar from the following sources: https://www.npmjs.com/package/ng2-daterangepicker http : // www. daterangepicker . com/ The issue I am encountering is with formatting the date output. Accordin ...

Adjusting the dimensions of the cropper for optimal image cropping

I am currently working on integrating an image cropper component into my project, using the react-cropper package. However, I am facing a challenge in defining a fixed width and height for the cropper box such as "width:200px; height:300px;" impo ...

Any suggestions on how to simulate data for the this.getResults$.subscribe method in Angular when testing unit cases?

showMessage(){ this.retrievedData$.subscribe(result =>{ if(result !== undefined && result !== null){ this.message = result.content; }else{ this.message="No Data"; }); } What is the best way to create mock data for testing the above method in ...

Integration of HostConfig with AdaptiveCards

Is there anyone familiar with incorporating a HostConfig to style AdaptiveCards using the webchat CDN in an Asp.Net Core environment? For instance, what should be the name of the file? And where exactly does it need to be placed? The specific setup for ...

Sharing data between two components in an Angular2-Meteor application

I am currently working with angular2-meteor. When attempting to transfer a value between two components (updating the value in the first component triggers an event in the second component where the new value is used), I have two methods available: The ...

Strategies for displaying error messages in case of zero search results

I am currently developing a note-taking application and facing an issue with displaying error messages. The error message is being shown even when there are no search results, which is not the intended behavior. Can someone help me identify what I am doing ...

Categorize items based on their defined attributes using Typescript

[origin object array and expect object array ][1] origin object array: 0: amount: 100000000000000000000 feeTier: 0.3 price: 00000 priceDecimal: 0000 status: "unknown" tokenXAddr: "0x*********" tokenXSymbol: "USDC" tokenYAddr: ...

The documentation for Angular guards is riddled with vague and obfuscating statements

I've been delving deep into Angular lately, and I found the documentation to be quite enlightening. currently, I'm focused on learning about guards. In my research, I came across this intriguing statement: The router evaluates CanDeactiva ...

Locate a specific item by its ID within a JSON file utilizing Angular version 2 or later

My JSON file structure is like the example below: { "id": "1", "country": "Brazil", "state": [ {"id": "1", "name": "Acre", "city": [ { "id": "1", "name": "Rio Branco"}, { "id": "2", "name": "Xapuri"} ...

Style will be applied to Angular2 when the object's ID exceeds 100

I am working with object markers that have different Id's assigned to them. Now, I am trying to apply additional styling when the id > 100. Check out the code snippet below: <span *ngIf="result.object.reference > 100" class="tooltip-data"&g ...

In Angular, use the ngFor directive to iterate through items in a collection and add a character to each item except

Currently, I am iterating through my data list and displaying it in the view using spans: <span *ngFor="let d of myData"> {{d.name}}, </span> As shown above, I am adding a comma ',' at the end of each item to ensure a coherent displ ...

What is the best method for extracting the selected value from a Dropdown in ng-bootstrap?

I am currently utilizing ng-bootstrap and I am interested in obtaining the selected value from a dropdown. <div class="col text-right"> <div ngbDropdown placement="top-right" class="d-inline-block"> <button class="btn btn-outline-primary ...