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

How can I combine multiple styles using Material-UI themes in TypeScript?

There are two different styles implementations in my code. The first one is located in global.ts: const globalStyles = (theme: Theme) => { return { g: { marginRight: theme.spacing(40), }, } } export const mergedStyle = (params: any) ...

Dependency mismatch in main package.json and sub package.json

Imagine you have a project structure in Typescript set up as follows: root/ api/ package.json web/ package.json ... package.json In the main package.json file located in the root directory, Typescript is installed as a dependency to make ...

What is the reason for the regeneration of the 2D array?

I have a method called generateWeights() that retrieves random values in an array; And a method named learn() that calls the changeWeights() method to alter the values in the array. Expected: Prior to invoking the learn() method, I anticipate receiving an ...

Maintaining the Continuity of an Observable Stream Post Error Emission

Have you ever wondered how to handle errors from an observable without ending the stream? For instance, when making HTTP calls and encountering a 404 error or another type of error, throwing an error in the stream will cause it to stop and trigger the err ...

The CanLoad guard does not permit access to the root route

My original idea was to create a project where the main website, located at "/", would only be loaded lazily after the user logs in. const routes: Routes = [ { path: '', canLoad: [AuthGuard], loadChildren: './home/home.module#HomeModule&a ...

Developing applications with Angular 4 and AppInventor window

Currently, I have a local Angular 4 application that utilizes localStorage on a desktop browser for data persistence. Within the application, I have implemented a WebViewer in AI. It is clear that localStorage cannot function in AI2, so alternative data s ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

When attempting to run a Typescript Playwright test in Visual Studio Code's debug mode, it inexplicably fails to execute

I am fairly new to TypeScript and Playwright, but I have experience in coding. I believe I have a good understanding of what I am trying to achieve, but I am encountering a problem that I can't seem to figure out. I'm hoping someone can help me. ...

Is there an alternative method to invoke the function aside from setTimeOut()?

if(i==1){ this.resetScreens(); this.editJobScreen1 = true; if(this.selectedLocations.length > 0){ this.locationService.getLocationByInput({ maxResultCount:16, skipCount: 0 }).subscribe((ele)=>{ ...

Implement Angular's Observable Subscription to fetch data from an API endpoint

Forgive me if I'm not using the correct terminology for Subjects and Observables. I am currently trying to subscribe to newImages in order to get a list of images. In my console, the response is as follows: [] [3] [7] [9] Each number represents ...

Retrieving information from a data file by implementing a GraphQL Apollo Server within a NextJS application route

Currently working with Next.js 14 (app route), React, and the GraphQL Apollo framework. I have a JSON file containing data saved locally that I'd like to display using the server API. How can I make this happen? Below is the JSON structure I need to r ...

Steps for Signing Up for a Collaboration Service

I'm struggling to understand how to monitor for new values in an observable from a service. My ultimate objective is to integrate an interceptor, a service, and a directive to show loading information to the user. I have set up an interceptor to liste ...

Is it possible to generate one or more observables for a particular topic within a service?

After researching various sources and websites, it is apparent that there are two distinct approaches to creating a service with a subject/observable for data sharing: One approach involves initializing an observable of the subject and returning it (refer ...

Get rid of the box-shadow that appears on the top side of mat-elevation

I placed a mat-paginator at the bottom of my mat-table which is styled with a mat-elevation-z4 class. However, when I added the mat-elevation-z4 class to the mat-paginator component as well, the upper shadow from the paginator appears to overflow onto the ...

Ways to boost the efficiency of your Ionic 4 app development process

I have created an Ionic 4 app with over 50 screens, including components and popups. The build and live reload process is taking a lot of time, especially for minor UI changes. Is there a way to speed up the development process? Here are my Environment Se ...

Guide to displaying the continent name on a 3D globe using Reactjs, TypeScript, and Threejs

I am currently working on integrating Threejs into my Nextjs 14 application to create a 3D earth globe using Gltf. However, I am facing an issue where I am unable to display the text of the continent name on their respective continents. I want to have fixe ...

The parameter 'any' cannot be assigned to the parameter 'never' - Array provided is incompatible

Currently delving into TypeScript and encountering an issue while setting a reducer in redux Toolkit. Here's the code snippet in question: const testSlice = createSlice({ name: "test", initialState: [], reducers: { callApi: (state, ...

Setting style based on the condition of the router URL

I am currently facing an issue with a global script in Angular 10 that is supposed to evaluate the current path and apply a style to the navigation bar conditionally. However, it seems to fail at times when using router links. I am wondering if there is a ...

Combining Angular, Node.js, and Spring Boot Java REST API to enable Angular Universal functionality

I am seeking guidance on integrating Angular with NodeJS and Spring Boot for my application. Currently, I have built a system that utilizes Angular for the frontend and Java/Spring Boot for the backend REST API. However, I have come across challenges with ...

Angular 2 or more variable binding

In this demonstration, only the unit-object will be saved: <select id="unit" name="unit" #unit="ngModel" class="form-control" [(ngModel)]="iu.unit" (change)="onDropdownChangeUnit($event)"> <option *ngFor="let i of UI_Units" [ngV ...