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

Automatically update the table in Python Flask every minute

I need help with my Flask code below. I want to automatically refresh the table data every 60 seconds. I have included the Setinterval function in HTML, but for some reason, it's not refreshing as expected. I'm struggling to pinpoint the exact is ...

Utilizing the map function in React to create a button reference

I am currently facing an issue that is relatively simplistic and doesn't have any real-world application. My goal is to locate a 'green' button and make it blink for a duration of 3 seconds. How can I achieve this using React? const btnLay ...

Retrieve objects from an array that contain a certain specified key

I am trying to extract the objects from All_reports that contain the key: comentarioAdmin. Currently, I am retrieving all reports from All_reports, but I only want the reports that have the key comentarioAdmin. Thank you! getReports() { this.Service.g ...

Rearrange an element in an array from last to first position using typescript

I am working with an array that looks like this var column = ["generic complaint", "epidemic complaint", "epidemic1 complaint", "epidemic2 complaint", "bal vivah", "name"] My goal is to move the last element of the array to the first position, resultin ...

Are we looking at a declaration of an arrow function? Is this concept even real?

I have been exploring the concept of function expressions versus function declarations with arrow functions. From my understanding, this is an example of an arrow function expression: const fred = greeting = () => { console.log("Hello from arrow ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

How to include images in a PDF using jspdf without encountering issues with Adobe Reader?

For a project I'm working on, I've integrated jspdf to convert some charts into a PDF. The framework I'm using is angularjs 1.5.6, and the charts are created with chart.js. The HTML snippet for the charts looks like this: <div name="char ...

Stopping the ability to navigate within an Ionic application

I am attempting to block navigation and display a popup in a controller. $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { if(someConditionMet) { event.preventDefault(); showPopup(); } } ...

Why do ES6 classes fail to set properties when an overloaded function is called within the constructor of the parent class?

I encountered a puzzling scenario while coding that has left me perplexed. Here's the situation: I am extending a class from a library, which serves as the "Parent"-class. It allows its subclasses to override the init-method for custom initialization ...

Why isn't Sequence.js Slider automatically playing?

Issue: The sequence.js slider I implemented is not animating. Despite adding the following options: animateCanvas: true, fadeStepWhenSkipped: false, autoPlay: true, autoPlayInterval, 2000 It still does not work. Is there something essential t ...

Detecting changes to DOM elements without using jQueryResponding to DOM element

Suppose I have the following HTML structure: <div id='content'></div> I want to receive an alert when there are height mutations on this element. I thought about using the MutationObserver class for this, but I encountered a specifi ...

Tips for invoking a PHP function with jquery

I'm facing a bit of an issue with my code. I have a button that, when clicked, should execute a PHP function defined in the same file. Although the "clicked" alert appears upon clicking the button, I'm not getting any response from the function. ...

Tips for effectively managing relationships in a RESTful API

Exploring the concept of REST architecture through the development of a RESTful service for an 'Issues Tracking Application'. In this application, users, projects, issues, and comments are integral components. The relationships are outlined as f ...

Getting JSON data from an Angular JS controller can be achieved by utilizing the built-in

My user login function includes a method called logincheck, which takes in parameters and sends a request to the server. Upon success, it redirects the user to the dashboard with the member ID. this.logincheck = function(log) { var pa ...

Employing a while loop within the context of a Promise

I am currently working on a user list and checking users with specific details. I'm utilizing sequelize js with express for this task. My query is whether it is possible to use a while loop in this manner to search and save data in the database. Any a ...

Obtain the name of the client's computer within a web-based application

I am working on a Java web application that requires the computer name of clients connecting to it. Initially, I attempted to retrieve this information using JavaScript and store it in a hidden form field. However, I discovered that JavaScript does not hav ...

Transforming JQuery text upon selecting preloaded content with fire

When I copy the first name into the last name field, everything works fine for new names on the page. However, once a few names have been entered and the browser starts showing a history of names, the function doesn't work anymore if a pre-filled or o ...

Emulate clicking a radio button (using PHP and JS)

For the past week, I've been struggling to solve this issue with no luck. I admit that I am new to this area, so I ask for your patience. My current problem involves using TastyIgniter, an online food ordering system. In order to add items to the car ...

Exploring the Power of Two jQuery Ajax Functions in Your Script

Is it possible to provide guidance on how I can successfully execute two separate Ajax calls within a single script without encountering conflicts? A sample of the current script structure is as follows: <script type="text/javascript"> $(document).r ...

Switching up the content of an HTML page with JavaScript or JQuery: what you need

Is it possible to update HTML content using JavaScript or JQuery? https://i.sstatic.net/EWOXg.png I am trying to change the contents from 1 to 5 in a sequential order based on the time shown in the image. How can I achieve this using JavaScript or JQuery ...