What is the best way to inject a service instance into the implementation of an abstract method?

In my Angular application, I have a service that extends an abstract class and implements an abstract method.

@Injectable({
  providedIn: 'root',
})
export class ClassB extends ClassA { 

constructor(
    private service : ExampleService) {
    super();
  }

  abstractMethod() {
   //this.service returns undefined here
  }

} 

export abstract class ClassA { 

  abstractMethod();
  
  otherMethod() { 
    this.abstractMethod();
  }
}

Nevertheless, in the constructor of ClassB, I face the challenge of injecting a service to be used within the abstract method.

The abstract method is called within "otherMethod()" in the Abstract class. Since the abstractMethod() has no implementation in the Parent class, it expects to find its implementation in the child class, but currently, it returns undefined.

How can I successfully utilize a service instance within the abstractMethod()?

To elaborate, I am striving to access a service instance inside "abstractMethod()", yet it currently results in returning undefined.

Answer №1

Reasons for Code Failure

  • this.service is invoked in abstract class ClassA.
  • ClassA does not recognize a service property.
  • Only ClassBService has access to the service property because it is marked as private.

Solution

  • Add a service property to ClassA.
  • Change the scope of your service property to either protected or public.

The following code performs similar functionality to what you desire

    import { Injectable } from "@angular/core";
    import { HelloService } from "./hello.service";
    
    abstract class ClassA {
      protected service: HelloService;
      public hello() {}
    
      protected say_hello() {
        this.service.hello();
      }
    }
    
    @Injectable()
    export class ClassBService extends ClassA {
      constructor(protected service: HelloService) {
        super();
      }
    
      public hello() {
        this.say_hello();
      }
  }

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

Have Vue props been set to null?

Currently, I have a component within my vue.js application that looks like this: export default { props: ['forums'], methods: { increment(forum, index) { ForumService.increment(forum) .then(() => { ...

Why does my chart.js disappear every time I perform a new render?

Hey there, I'm facing an issue with my code. Let me paste what I have... import React, { memo, useEffect } from 'react'; import Chart from "chart.js"; /* redux-hook */ import { useSelector } from 'react-redux' const lineChart = m ...

What is the best way to display multiple HTML files using React?

Looking to develop a web application using React that consists of multiple HTML pages. For instance, login.html and index.html have been created and linked to URIs through the backend - resulting in localhost:8080/login and localhost:8080/index. However, R ...

Top method for dynamically loading a specific component by using its selector as a variable

I'm currently in the process of developing a straightforward game using Angular. The game is structured to consist of multiple rounds, each with unique characteristics that are distinguished by the variable roundType. For instance, round types can in ...

Tips on maximizing efficiency in number game coding

Seeking to create a number using a specified set of 6+ inputs. For instance, aiming for the number 280 with inputs [2,4,5,10,30,50,66], the desired output format would be something like this: ((2+5) * 4 * 10). Each input number can only be used once per s ...

A step-by-step guide on retrieving a value from a DateTime picker in a React application

I am utilizing Material-UI to create a DateTime picker. You can check out my demo code here. In order to observe the current selected value, I have added console.log to the function handleChange. However, I am facing an issue where the value does not chan ...

Leverage Vue3's v-html feature without the need for additional wrapping tags by using script

Is it possible to use Vue's v-html directive within a Vue 3 <script setup> setup without needing an additional wrapping tag? I am looking to achieve something similar to the following: <script setup> const html = ref(`<pre></pre& ...

There seems to be a problem fetching the WordPress menus in TypeScript with React and Next

Recently I've started working on a project using React with TypeScript, but seems like I'm making some mistake. When trying to type the code, I encounter the error message: "TypeError: Cannot read property 'map' of undefined". import Re ...

How can React and Redux ensure that response data is accessible to every component?

When using react and redux, how can data written in the useDispatch function be made available in other components? Additionally, how can the customerId be accessed in all components? I have created a code that calls an API and returns data in response. I ...

I must adjust the size of images based on the size of the viewer's screen

Hello everyone, I could really use some assistance as I am not an expert programmer but just a site admin. My issue is this: I have a website running on PHP and I want to display images to my members while keeping them within specific size limits so they ...

What are the specific extensions for email validation?

code for the form: <form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" > <p class="email"> <label for="budget">Expected Budget ...

Learn how to implement a vertical bar chart in Highcharts by using it as a component and passing it as props

I recently imported a Bar Chart component from Highcharts, but it is being displayed horizontally. I would like to convert it into a vertical chart instead. Can someone please assist me in achieving this by passing the necessary props? <template v-slot ...

Seeking assistance with basic Javascript/Jquery for Ajax on Rails 3 - can anyone help?

I've been diving into JavaScript and hit a roadblock. At the moment, I have a very basic gallery/image application. My goal is to create a functionality where clicking on an image will lead the user to a URL stored in my model data using AJAX. Additi ...

Effortlessly sending information to the Material UI 'Table' element within a ReactJS application

I have integrated a materialUI built-in component to display data on my website. While the code closely resembles examples from the MaterialUI API site, I have customized it for my specific use case with five labeled columns. You can view my code below: h ...

Issue arises when attempting to render a component while utilizing window.location.pathname and window.location.hash in conjunction with a navigation bar

I am encountering a problem when attempting to render a react component using a navigation bar. I have experimented with both Switch case and if-statement methods. The first approach involves using window.location.hash, which successfully alters the URL u ...

When incorporating pinia with Vue, encountering an error with the decorator that says "Error: Unable to access 'useCoreStore' before initialization" may happen

While implementing the vue-facing decorator in my current project, I encountered an issue with setting up pinia. The structure of my component resembles the example provided here: I have verified that decorators like @Setup are functioning correctly, ind ...

Step-by-step guide to setting up a TypeScript project on Ubuntu 15 using the

As a newcomer to UBUNTU, I have recently ventured into learning AngularJS2. However, when attempting to install typescript using the command: NPM install -g typescript I encountered the following error message: view image description here ...

Is there a built-in method or library for extracting data from JSON strings in programming languages?

Duplicate Query: how to parse json in javascript The data sent back by my server is in JSON format, but it doesn't follow the usual key/value pairs structure. Here's an example of the data I'm receiving: ["Value1","Value2","Value3"] ...

Creating a custom script for a search field that retrieves information from an XML document

Attempting to create a script that iterates through an XML file, the provided code currently displays alerts but fails to show information when a valid value is entered into the search field. However, upon removing the error checks and keeping the final ...

The modal appears on the screen prior to the content being shown

While attempting to render a bootstrap modal with content from a REST call, I am encountering an issue where the modal appears before the content has finished populating. The modal is triggered by a button click event. If I click the button again after wa ...