Incorporate a service into a base class in Angular2 to ensure its functionality extends to all derived classes

I have multiple classes with a hierarchical inheritance structure as follows:

  • class A (an abstract class)
  • class B extends A
  • class C extends B

I am looking to incorporate a service into class A to enable a function that utilizes notifications. How can I achieve this without directly adding the service to the subclasses?

My approach is somewhat similar to the example below, but I aim to find a way to avoid importing the service in the subclasses:

export class abstract A {
  constructor(protected service: NewService) {}
}

export class B extends A {
  constructor(protected service: NewService) {
    super();
  }
}

export class C extends B {
  constructor(protected service: NewService) {
    super();
  }
}

Answer №1

In my opinion, the most effective way to achieve this is by incorporating an Injector into an abstract class. This allows for the injection of multiple services. Subsequently, the injector should be passed into the super() method in each descendant class.

import { Injector } from '@angular/core';

export abstract class Base {
  private serviceA: ServiceA;
  private serviceB: ServiceB;

  constructor(
    injector: Injector
  ) {
    this.serviceA = injector.get(ServiceA);
    this.serviceB = injector.get(ServiceB);
  }
}

export class Child extends Base {
  constructor(
    private injector: Injector
  ) {
    super(injector);
  }
}

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 to simultaneously call two APIs and then immediately call a third one using RXJS?

I am looking to optimize the process of making API calls by running two in parallel and then a third immediately after both have completed. I have successfully implemented parallel API calls using mergeMap and consecutive calls using concatMap, but now I w ...

When initialized within an object, Angular may identify a field as undefined

Whenever I attempt to access a property of the object named "User," it shows up as undefined. However, upon logging the complete object to the console, the field appears with the necessary data. Here is the console log output: perfil.component.ts:42 unde ...

Angular 4 prohibits certain special characters and the number zero

Currently, I am a beginner in Angular 4 and I am working on learning how to search for data from a text box. However, whenever I input special characters like "%" in my code, it triggers an error leading to a crash in my application. Is there any effectiv ...

When working with TypeScript in Node, the module ""http"" does not have a default export available

const httpModule = require('http'); httpModule.createServer((req, res) => { res.end('Hello World'); }).listen(3000, () => console.log('Server is running on port 3000')); I've installed @types/node but ...

The Highcharts xrange series is encountering the error message "x is not a function."

I am currently working in an Angular 4 (Angular-cli) environment and attempting to utilize the x-range highcharts type. After executing the npm install command npm install highcharts --save, I included these lines of code: import * as Highcharts from &ap ...

Updating Facebook meta tags dynamically in Angular 4 to enhance Open Graph integration

Is there a way to dynamically update meta tags for Facebook/Whatsapp share dialog? I recently upgraded my angular 2 application to angular 4 in order to utilize the Meta service and update meta tags dynamically once data is retrieved from an API. Within ...

Experience a captivating Angular slideshow carousel that resets when you click on a dot button, all powered by the magical capabilities of

Check out this Stackblitz Link for a working sample. I have developed an angular carousel slider component using rxjs. Each slide changes after 5 seconds and everything is working smoothly. However, I am facing an issue where clicking on a particular dot ...

Encountering a Nuxt error where properties of null are being attempted to be read, specifically the 'addEventListener' property. As a result, both the default

Currently, I am utilizing nuxt.js along with vuesax as my UI framework. I made particular adjustments to my default.vue file located in the /layouts directory by incorporating a basic navbar template example from vuesax. Subsequently, I employed @nuxtjs/ ...

Maintaining checked items in their original state while searching for another one in ion-searchbar can be achieved by properly handling

My goal is to maintain the checked items as checked when searching for another item in ion-searchbar. While I have managed to keep the checked items, the checkmark icon does not stay checked. What I aim for is to retain the checked state of all food items ...

Include a tab button within a vertical tab list using Angular Material

I have utilized Angular Material to create a vertical tab, and I would like to incorporate an Add Tab button within the tab listing itself. Currently, when I add the button, it appears at the bottom of the layout instead. For reference, you can access the ...

Export interface for material-ui wrapper to cast any type in TypeScript (React)

I work with React using TypeScript. Recently, I encountered an issue with exporting. I'm creating an interface that encapsulates components from Material-ui. Here is a simplified example: Wrapping.tsx import { default as Component, ComponentProps ...

Is it possible to transfer parameters from one page to another page using the pop method in Ionic 2?

Is it possible to pass parameters from one page to another during a push operation, but how can this be done during a pop operation? showfilter(){ this.navCtrl.push(FilterPage,{ fulldetail : this.selectedarea }); } Can you explain how ...

Unlocking Not Exported Type Definitions in TypeScript

Take a look at this TypeScript code snippet: lib.ts interface Person { name: string; age: number; } export default class PersonFactory { getPerson(): Person { return { name: "Alice", age: 30, } } } ...

Guide to running asynchronous code synchronously in Angular 5

Currently, I have a function that loops through a list of files and for each file, it triggers an async method to manipulate the image and add it to an array. The problem is that the async calls are occurring simultaneously, causing the UI to freeze. My g ...

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 ...

The Angular Tooltip feature is unable to interpret the characters "' '" or "' '"

Let me explain the scenario: I am receiving a list of objects from my back-end service, which I then break apart using ngFor and display accordingly. Each item in the list has an associated toolTip that provides additional information. The info for each i ...

What are the conditions for Jasmine's .toHaveBeenCalledWith to match the parameters?

I'm working on an Angular service along with its Jasmine test. The test is calling f1() and spying on f2(). The function f2 takes a variable v2 and updates it by setting field 'a' to 3. I expected the function f2 to be called with v2 (as def ...

Encountered an issue when attempting to send data using this.http.post in Angular from the client's perspective

Attempting to transfer data to a MySQL database using Angular on the client-side and Express JS on the server-side. The post function on the server side works when tested with Postman. Here is the code snippet: app.use(bodyParser.json()); app.use(bodyPa ...

Is it possible to continuously activate an Angular Input setter using a Subject?

Is there a way to activate an @Input setter without providing a value, by utilizing RxJS' Subject()? It seems that the setter only gets triggered once, most likely because no value has been changed. How can I ensure that the input is activated every ...

Angular2 - Actively selecting a checkbox in an ngFor loop with a reactive form

There is an object retrieved from a database that consists of a list of names with their corresponding IDs, as well as a flag to indicate whether they are selected or not. Object: let items = [{ ID: 1, Name: 'Item A', Selected: 'Y ...