Extending injections in Angular 5 by inheriting from a base class

I have created a class with the following structure:

@Injectable FooService {

    constructor(protected _bar:BarService){

    }
}

Then, I extended this class as shown below:

@Injectable ExtFooService extends FooService {

    constructor(_bar:BarService){
        super(_bar);
    }
}

However, I decided to further extend the BarService class like so:

@Injectable ExtBarService extends BarService {

   public myBarVar = "myBarVar";

    constructor(){
        super();
    }
}

Now, in another part of my codebase:

@Injectable ExtFooService extends FooService {

    constructor(_bar:ExtBarService){
        super(_bar);
    }

    someMethod(){
        return {
            key: this._bar.myBarVar
        };
    }
}

But suddenly, an error pops up:

Error:(51, 28) TS2551:Property 'myBarVar' does not exist on type 'BarService'.

It seems that ExtBarService is being treated as a BarService because of the superclass requirements. Could there be a solution?

@Injectable ExtFooService extends FooService {

    constructor(_bar:BarService, private _extBar: ExtBarService){
        super(_bar);
    }

    someMethod(){
        return {
            key: this._extBar.myBarVar
        };
    }
}

Answer №1

Overriding a private field is not allowed in the derived class, and attempting to access it may result in an error. It seems like there might be missing parts of your code causing confusion.

To resolve this issue, consider changing the field to protected. This way, it will remain inaccessible from outside classes but can be accessed by derived classes. You can then override the type with a different service without encountering any errors:

@Injectable class FooService {
    constructor(protected _bar:BarService){
    }
}

@Injectable class ExtFooService extends FooService {
    constructor(protected  _bar:ExtBarService){
        super(_bar);
    }

    someMethod(){
        return {
            key: this._bar.myBarVar
        };
    }
}

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

Angular ngModel not updating both directions in data binding

<input matInput placeholder="username" [(ngModel)]="userId"> <input matInput placeholder="name" [(ngModel)]="name"> I have made sure to import the FormsModule in my Angular project. import { FormsModule ...

Why does the server attempt to load the chart in Angular 10 Universal using Amcharts 4?

I have experience with Angular, but I am now delving into the world of using Universal for SEO purposes. My goal is to integrate a map from amcharts 4, which works fine without Angular Universal. However, I am facing an issue where the server attempts to ...

Converting a string to Time format using JavaScript

I am working with a time format of 2h 34m 22s which I need to parse as 02:34:22. Currently, I am achieving this using the following code: const splitterArray = '2h 34m 22s'.split(' '); let h = '00', m = '00', s = &a ...

Steps to display a modal dialog depending on the category of the label

I'm encountering an issue where clicking on different labels should show corresponding modal dialogs, but it always displays the same modal dialog for both labels ("All Recommendations"). Can anyone offer guidance on how to resolve this problem? Thank ...

typegrapql encounters an issue with experimentalDecorators

I'm currently delving into TypeGraphQL and working on building a basic resolver. My code snippet is as follows: @Resolver() class HelloReslover { @Query(() => String) async hello(){ return "hello wtold" } } However, ...

How to generate a new array in Angular by combining elements from two existing arrays for common items

I am currently working on a TypeScript function to compare two arrays and generate a third array containing the common items. For example: employees: any; offices: any; constructor() { this.employees = [ { fname: "John", lname: "James", sta ...

Tips for transfering variables from an electron application to the backend of an Angular project

My goal is to develop a website and desktop application using the same code base. However, due to some minor differences between the two platforms, I need a way for my Angular app to distinguish whether it has been called from the web or from Electron. I& ...

Display the length of the product array when I have multiple JSON objects

I am working with the following JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "_id": "12123", "dateCreated": "2019-12-03T13:45:30.418Z", "pharmacy_id": "011E7523455533 ...

What is the process for updating the internal TypeScript version in VS Code?

When using VS Code, I noticed it comes with its own TypeScript version: Is there a way to update this? The current version is 4.9.3. ...

Ways to retrieve data beyond the constructor

Here is the code snippet from my component.ts: export class OrganizationsComponent { public organizations; constructor(public access: OrganizationService) { this.access.getOrganizations().subscribe((data => { this.organizations = data; ...

Can optional properties or defaults have a specific type requirement defined for them?

When defining a type for a function's input, I want to designate certain properties as required and others as optional: type Input = { // Required: url: string, method: string, // Optional: timeoutMS?: number, maxRedirects?: number, } In ...

Stop MatDialog instance from destroying

In my application, I have a button that triggers the opening of a component in MatDialog. This component makes API calls and is destroyed when the MatDialog is closed. However, each time I open the MatDialog for the second time by clicking the button agai ...

Guide on properly documenting custom function types in JSDoc or TypeScript to ensure accurate referencing for VSCode IntelliSense functionality

I am currently working on documenting custom function types within an object and would greatly appreciate any assistance: A Closer Look at the Issue Consider this basic object declaration with several function properties (addCoordinate, addCoordinateOne, ...

The router is unable to direct when an item is clicked

I am encountering an issue with my routing setup - when I click on an item in the list-item component, it does not successfully route to the detail-component. Here is a glimpse of my source code: product-list.component.html: <h1>Product List Compon ...

Guide to reference points, current one is constantly nonexistent

As I work on hosting multiple dynamic pages, each with its own function to call at a specific time, I encounter an issue where the current ref is always null. This poses a challenge when trying to access the reference for each page. export default class Qu ...

Having difficulty removing new or existing lines on StackBlitz

I attempted to experiment with React on StackBlitz, but I encountered a problem where I couldn't delete any lines of code. It seems that while I can add new lines of code, deleting them is not an option. Even when logging in with GitHub, the issue per ...

Refreshing the cache in SWR, but the user interface remains unchanged inexplicably - SWR hook in Next.js with TypeScript

I am currently working on a project that resembles Facebook, and I am facing an issue with the like button functionality. Whenever I press the like button, I expect to see the change immediately, but unfortunately, SWR only updates after a delay of 4-8 sec ...

A guide on accessing a dynamic object key in array.map()

How can I dynamically return an object key in array.map()? Currently, I am retrieving the maximum value from an array using a specific object key with the following code: Math.max.apply(Math, class.map(function (o) { return o.Students; })); In this code ...

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...

The use of findDOMNode has been marked as outdated in StrictMode. Specifically, findDOMNode was utilized with an instance of Transition (generated by MUI Backdrop) that is contained

I encountered the following alert: Alert: detectDOMNode is now outdated in StrictMode. detectDOMNode was given an instance of Transition which resides within StrictMode. Instead, attach a ref directly to the element you wish to reference. Get more inform ...