Adding dependency service to the parent class in Angular

I am working with classes parent and child. The child class is an extension of the parent class. I want to inject the injectable class service into the parent class since all instances of the child class will be using it as well. Can someone guide me on how to achieve this?

Answer №1

To access any service or class from the parent component, you can utilize the Injector class. By injecting the Injector class in the child component and passing it to the parent using super(injector), the parent component can then inject reusable services from the child's injector.

Example of Parent Component :

export class BaseComponent implements OnInit {

    protected myService: MyService;

    constructor(injector: Injector) {
        this.myService = injector.get(MyService);
    }

    ngOnInit() {
        console.log('ngOnInit from Base');
    }
}

Example of Child Component :

export class AppComponent extends BaseComponent {

  constructor(injector: Injector) {
    super(injector);
  }

  ngOnInit() {
    super.ngOnInit();
    this.myService.getUsers();
  }
}

This approach eliminates the need to individually inject each service from the child component to the parent component. Instead, it provides a more efficient way to inject services from the parent component.

Answer №2

Angular doesn't automatically instantiate a parent class, so you can't inject a dependency into it directly. The workaround is to make the child classes injectable and pass the dependencies up using super.

class Parent {
    constructor(protected someService: SomeService) { }
}

@Injectable()
class Child extends Parent {
    constructor(someService: SomeService) {
        super(someService);
    }
}

If the parent class doesn't require the dependency itself, it's recommended to mark the child classes as @Injectable() instead, allowing them to have their own private reference to the dependency.

Answer №3

To prevent the need to continuously pass either the injector or the injected instance from the child class to the parent class, consider utilizing the following alternative approach.

Start by creating a class with a single static property:

export class AppServices {
    static injector: Injector;
}

Next, assign a value to the injector within the module where your service is initialized:

import {Injector, NgModule} from '@angular/core';    
@NgModule({
      providers: MyService
    })
    export class AppModule {
      constructor(private injector: Injector) {
        AppServices.injector = this.injector;
      }
    }

Once the module has been instantiated, you can utilize the static injector in any class to access any of the module's services:

export class ParentComponent {
  private myService: MyService;

  constructor () {
     this.myService = AppServices.get<MyService>(MyService);
  }
}

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

Is there a way for me to deduce types dynamically?

Is there a way to dynamically infer types, similar to a union type? I am trying to register multiple elements from different parts of the code using a method like registerElement(...), but I am struggling with inferring these new types in TypeScript. This ...

Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet: this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); ...

What is the process of sending an HTTP post request in Angular 4 Universal?

Currently, I am working with Angular 4 Universal and attempting to send emails through a contact form using nodemailer. However, I am encountering issues with posting data via http.post. Contact Template HTML: <form (ngSubmit)="onSubmit()"> & ...

Typescript validation of tokens using Azure functions

Currently working on a website utilizing Azure Static Web App, where the login/registration is managed by Azure B2C. The backend API consists of typescript Azure functions integrated with Azure Static web app. Certain API calls can only be accessed when th ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...

Replace pipeline function during component testing

During my unit testing of a component that utilizes a custom pipe, I encountered the need to provide a fake implementation for the transform method in my test. While exploring options, I discovered that it's feasible to override components, modules, ...

Struggling to dynamically create form controls within Angular forms and receiving the following error in the console: "TypeError: feature_r5.get is not a function"

When I click a button in my Angular v14 HTML template, I am trying to dynamically generate form controls and although I am able to generate them, an error is popping up in the console. ERROR TypeError: feature_r5.get is not a function at PostAdvComponent_ ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

What causes parameters to be undefined when making a DELETE request in my Next.js application running on version 14.1.4?

I am encountering an issue with my DELETE mapping export async function DELETE({params} : {params: {id: string}}) { try { const loanToDelete = await prisma.loan.findUnique({ where: { id: parseInt(params.id) } }) if (!loanToDelete ...

VS Code is flagging TypeScript errors following the recent software update

After updating my VS Code, I started seeing TypeScript error messages like the following: ButtonUnstyled.types.d.ts: Module '"/components/node_modules/@types/react/index"' can only be default-imported using the 'esModuleInterop&a ...

Tips for ensuring the angular FormArray is properly validated within mat-step by utilizing [stepControl] for every mat-step

When using Angular Material stepper, we can easily bind form controls with form groups like [stepControl]="myFormGroup". But how do we bind a FormArray inside a formGroup? Constructor constructor(private _fb: FormBuilder){} FormArray inside For ...

Is there any benefit to making the SVG elements width and height 100%?

The Angular Material documentation app features an SVG Viewer that is able to scale the SVG content to fit the container using the following function: inlineSvgContent(template) { this.elementRef.nativeElement.innerHTML = template; if (this.sca ...

New post: "Exploring the latest features in Angular

Looking for help with integrating Angular and SpringREST to fetch data from the backend? Here's my situation: I need to retrieve a JSON string from the backend using a POST request, send it to my site's hosted link, and display it on the user int ...

Using type definitions in non-TS files with VSCode: A beginner's guide

My code is not in TypeScript, shown here: // foo.js module.exports = app => { // some logic here } I want to enhance my development experience by using TypeScript definition files to specify the type of the argument app, enabling VSCode to provide ...

PrimeNG's Angular component pTree TreeNode

Is there a way in Angular to retrieve the positions of nodes within a TreeNode hierarchy based on their display order? I have data structured as TreeNode objects, which include children that can branch off further. How can I access these nodes according t ...

How can you expand the class of a library object in Animate CC using Createjs?

I am currently in the process of migrating a large flash application to canvas using Typescript, and I'm facing challenges when it comes to utilizing classes to extend library objects. When working with a class library for buttons, class BtnClass { ...

Data is not being displayed in the Angular table

Currently, I am working on developing a time tracking application as part of a project. However, I have encountered an issue while attempting to showcase all the entries in a table format (as shown in the image below). Despite having two entries according ...

Is it possible to define data types for the global context in cucumber?

Embarking on a fresh cucumber-selenium project in Typescript, I am eager to keep the Driver in the world context. However, following the method suggested here, I encounter an issue where the Driver type remains inaccessible to step definitions. This means ...

Setting a default value for the dropdown in Angular is essential for ensuring a smooth

<select [(ngModel)]="detail.State" (ngModelChange) ="onStateChange()" class="form-control"> <option [ngValue]="null" disabled selected>Select State</option> <option * ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...