Utilize the power of generics with Angular's service providers

Is it possible to make the membervar of class Parent generic instead of type any, while still retaining the ability to switch provider classes without having to update all components that rely on class Parent? For example, if class ChildB implements a different type for class Parent than class ChildA.

export abstract class Parent {
  membervar: any;
}
export class ChildA extends Parent {
  constructor() {       
    super();
    this.membervar = ObjectA();
  }
}
export class ChildB extends Parent {
  constructor() {       
    super();
    this.membervar = ObjectB();
  }
}

In my app.module.ts, I can change the provider class by:

...
providers: [ { provide: Parent, useClass: ChildA } ]
...

There are components in the application that depend on the above structure:

export class SomeComponent {
  constructor(private aService: Parent) {

  }
}
export class SomeOtherComponent...
  constructor(private aService: Parent)...

Answer №1

class SpecializedComp<S> {
    constructor(protected specializedService: S) {}
}

class NewComp extends SpecializedComp<DataService> {
    newFn() {
        // this.specializedService -> is of type DataService
    }
}

If you prefer the parent to use the Class as a Parameter

class NewComp extends SpecializedComp<NewComp> {
    newFn() {
        // this.specializedService -> is of type NewComp
    }
}

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

Combining existing CSS classes with node labels in Cytoscape JS for Angular: A Guide

My project follows a consistent CSS theme, but the node's CSS style doesn't match. I'm looking to adjust the label colors in the CSS based on whether it's day mode or night mode. How can I accomplish this? this.cy = cytoscape({ con ...

Creation of source map for Ionic 2 TypeScript not successful

Struggling with debugging my Ionic 2 application and in need of guidance on how to include souceMap for each typescript file that corresponds to the javascript files. Despite enabling "sourceMap":true in my tsconfig.json file, the dev tools in Chrome do n ...

How can you optimize the storage of keys in JS objects?

Just pondering over this scenario: Consider a line definition like the one below, where start and end are both points. let ln = { s: {x:0, y:0}, e: {x:0, y:0}, o: 'vertical' } Now imagine having a vast array of lines, how can we sav ...

There is an issue with the property 'updateModf' in the constructor as it does not have an initializer and is not definitely assigned

When working with an angular reactive form, I encountered an issue. After declaring a variable with the type FormGroup like this: updateModf:FormGroup; , the IDE displayed an error message: Property 'updateModf' has no initializer and is not def ...

How to arrange table data in Angular based on th values?

I need to organize data in a table using <th> tags for alignment purposes. Currently, I am utilizing the ng-zorro table, but standard HTML tags can also be used. The data obtained from the server (via C# web API) is structured like this: [ { ...

The error message from ANGULAR states that it cannot locate the control with the specified path: 'childrenFormArray -> [object Object] -> gender'

I'm currently working on an angular project and facing a challenge in adding multiple children with their age and gender dynamically using reactive forms. Although I can add the form, I am having trouble with the delete functionality as it keeps throw ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

What is the best way to navigate back to the previous page while retaining parameters?

Is there a way to return to the previous page with specific parameters in mind? Any suggestions on how to achieve this? import {Location} from '@angular/common'; returnToPreviousPage(){ this._location.back(); } What I am looking ...

Designing a personalized mat-icon using the Github SVG

Trying to create a unique custom SVG mat-icon by loading the SVG directly from Github. My initial attempt using DomSanitizer was documented in this article, and it successfully loaded the SVG via HttpClient. Now, I am attempting to achieve this directly t ...

Having difficulties testing the Angular HTTP interceptor with Karma and Jasmine

Testing an http interceptor has been quite the challenge for me. Despite having my token logged in the console and ensuring that the request URL matches, I still can't figure out why it's not working with the interceptor in place. Interestingly, ...

Troubleshooting: Issues with APIGateway's Default Integration

I'm currently utilizing the AWS CDK to construct my API Gateway REST API My objective is to have my RestApi configured to automatically return an HTTP 404 error, so I set it up as follows: this.gateway = new apigw.RestApi(this, "Gateway", { ...

Tips for properly defining path names in loadChildren for lazy loading in Angular 2 NgModules

When setting correct path names for loadChildren in the app-routing.module file within an Angular 2 NgModule, I encountered some issues. Despite following the NgModule concept outlined on the Angular main website, I still couldn't find clear informati ...

The PrimeNG table fails to refresh upon initial modification

I'm working with a prime-ng table of shops, where I have the ability to remove and add shops to a list. The scenario: Whenever a shop is added, the ChildComponent emits an event to the ParentComponent, which then adds the shop to the list and updates ...

Testing Angular combineLatest with Jest

I'm encountering a challenge in an assessment involving a complex Statement related to combineLatest. Here is the snippet of code: component: export class ErinnerungenErinnerungenComponent implements OnInit, OnDestroy { ... erinnerungen: Erinne ...

Updating Select Options Disabled/Enabled in Angular 2

In my Angular2 project, I have 2 select elements: <div ng-controller="ExampleController"> <form name="myForm"> <label for="companySelect"> Company: </label> <select name="companySelect" id= ...

I'm facing an issue in Angular 4 where the routing for a child component is

I'm currently working on implementing routing in my Angular app for movies. I've set up a movie component and an edit movie component. The edit movie component is nested within the movie component, as shown in the folder structure below: https: ...

Displaying data from a JSON object to a DOM table can be achieved by dynamically generating table columns based on the keys within

There is a JSON object that I'm working with: [ { "SysID": "4", "Defect Classification": "Wrong Image Color", "1": "3.0", "2": "", "3": " ...

The storage does not reflect updates when using redux-persist with next-redux-wrapper in a Typescript project

I'm currently working on integrating redux-persist with next.js using next-redux-wrapper. However, I'm facing an issue where the storage is not updating and the state is lost during page refresh. Below is my store.ts file: import { createStore, ...

Grails3 and Angular profile as the default deployment configuration

What is the most effective approach to deploy the Grails3 war with an Angular profile (specifically Angular2)? My project is in Grails 3.2.9 and runs smoothly in development mode. I'm looking for a streamlined gradle build command that can create a co ...

Unable to retrieve shared schema from a different schema.graphql file within the context of schema stitching

In my project, I have a user schema defined in a file named userSchema.graphql; id: String! userName: String! email: String! password: String! } In addition to the user schema, I also have separate schema files for login and register functionalit ...