Injecting a service into a base class in Angular/TypeScript without injecting it into a sub-class

I am working with a basic ServiceBase class that has Http injected into its constructor:

import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

export abstract class ServiceBase<T> {
    constructor(private http: Http) {
    }

    protected getData(url: string): Promise<T> {
        return this.http.get(url).toPromise()
            .then(response => response.json() as T)
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.log('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

The child class then extends the functionality of the base class:

@Injectable()
export class WeatherService extends ServiceBase<Weather> {
    constructor(http: Http) {
        super(http);
    }

    getWeather(): Promise<Weather> {
        return this.getData('api/weather');
    }
}

Currently, I have to inject Http into each child class and pass it to the parent class using super(http);. Is there a way to avoid this repetitive injection and pass-through? Since the child classes will be utilizing methods from the parent class which already includes the Http service.

Answer №1

Indeed, utilizing the ReflectiveInjector makes it achievable.

import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

export abstract class ServiceBase<T> {

    protected http: Http;
    
    constructor() {
      const injector = ReflectiveInjector.resolveAndCreate([
      Http,
      BrowserXhr,
      {provide: RequestOptions, useClass: BaseRequestOptions},
      {provide: ResponseOptions, useClass: BaseResponseOptions},
      {provide: ConnectionBackend, useClass: XHRBackend},
      {provide: XSRFStrategy, useFactory: () => new CookieXSRFStrategy()},
    ]);
     this.http = injector.get(Http);
    }

    protected getData(url: string): Promise<T> {
        return this.http.get(url).toPromise()
            .then(response => response.json() as T)
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.log('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

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 it possible to directly declare multiple variables within an array in TypeScript?

I am looking to simplify my variable declaration process for an array in my Angular 8 project using TypeScript. Currently, my code looks like this: export class GridComponent { pizza0: Pizza; pizza1: Pizza; pizza2: Pizza; pizza3: Pizza; pizza ...

Having trouble with Angular npm install after pulling from Git repository?

I'm facing an issue where the Angular project I pull from git has a version of angular ^7.1.0, but my local global version is angular 8. Your global Angular CLI version (8.3.5) is higher than your local version (7.3.9). The local Angular CLI version ...

Ways to shift placeholder text slightly to the right within a select dropdown?

Struggling with this issue for hours, I can't seem to figure out how to: Adjust the position of the placeholder text (Search) by 10 pixels to the right in my select component Reduce the height of the field (maybe by 5px) without success. Could someo ...

The function signature '(event: ChangeEvent<HTMLInputElement>) => void' does not match the expected type 'ChangeEvent<HTMLInputElement>'

This is my first time using TypeScript to work on a project from the ZTM course, which was initially written in JavaScript. I am facing an issue where I am unable to set a type for the event parameter. The error message I receive states: Type '(event: ...

Guide to Integrating Pendo with Angular 8 and Above

I'm having some trouble setting up Pendo in my Angular 8 application. The documentation provided by Pendo doesn't seem to align with the actual scripts given in my control panel. Additionally, the YouTube tutorials are quite outdated, appearing t ...

Is there a way to reveal only the version information from the package.json file in an Angular 17 project?

Is there a secure way to extract and display only the version from a package.json file on the UI of a web application without exposing the rest of its contents? I am currently using the following structure in my package.json: { "name": "exa ...

Watching videos is quite a time-consuming process due to the long loading times

I recently created a website at , and I am facing an issue with the homepage video taking too long to play. While it works fine on a PC, it seems to load very slowly on mobile browsers. Any suggestions on how I can improve its loading speed? <video cl ...

Exploring ways to retrieve checkbox values instead of boolean values upon submission in Angular

I am currently working with a template-driven form and facing an issue. Despite receiving true or false values, I actually need to retrieve the value of checkboxes. <form #f = "ngForm" (ngSubmit) = "onClickSubmit(f.value)"> ...

What is the best method for altering a route in React while utilizing Typescript?

I recently started coding along with the ZTM course and am working on a face recognition app. Instead of using JavaScript, I decided to use TypeScript for this project in order to avoid using the any type. However, as a beginner in this language, I'm ...

What is the procedure for utilizing custom .d.ts files in an Angular 15 project?

Currently, within my Angular 15 project, I am utilizing a package called bootstrap-italia. This particular package is dependent on the standard Bootstrap package and includes additional custom components and types. However, it should be noted that this pac ...

Acquiring the handle of ngComponentOutlet

I am dynamically creating a component using ngComponentOutlet. Here is an example: import {Component, NgModule} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' @Component({ selector: 'alert-success& ...

How can I stop the SvelteKit production node server from filling up the logs with "Error: not found /path/here"?

After developing a website using sveltekit, I decided to build it for production as a nodejs server and deploy it on my linux server with Caddy as a reverse proxy. Unexpectedly, upon starting the server, I began receiving error messages in the log such as ...

What is the best way to incorporate padding into an Angular mat tooltip?

I've been attempting to enhance the appearance of the tooltip dialog window by adding padding. While adjusting the width and background color was successful, I'm encountering difficulties when it comes to styling the padding: https://i.sstatic.ne ...

What could be causing the table to display empty when we are passing data to the usetable function?

Visit Codesandbox to view Table While the header appears correctly, I noticed something strange. When I console log the data props, it shows all the necessary data. However, when I try to console.log row, there doesn't seem to be any single object re ...

Changing the background color dynamically of a table header in Angular Material

I have utilized the angular material table following this example. https://stackblitz.com/angular/jejeknenmgr?file=src%2Fapp%2Ftable-basic-example.ts In this case, I modified the heading color with the following CSS code. .mat-header-cell { backgrou ...

How to Evaluate the Performance of Your Angular Application?

After developing an Angular application, I want to evaluate the performance of my Angular component methods. For example, I want a tool that can show me how much time a method like getDetails() is taking, allowing me to make necessary improvements. The sam ...

Issue encountered when trying to showcase information using Angular from a JSON service within a DataTable

In an attempt to showcase data retrieved from a service connected to a mock json API, I encountered an issue. Upon clicking the button, the data is sent to the component for display in a Datatable. However, the problem lies in the fact that the data is not ...

What is the best approach to dynamically update CSS using onChange in TypeScript?

I am facing an issue with 2 input fields on my website. I want to create a functionality where if a user enters data into one field, the CSS of the other field changes dynamically. For instance, I would like to change the class "changeAmount" to "display:n ...

Specialized purpose for typed arrays

Given an array containing elements of two different entities: interface A { type: string } interface B { type: number } const a = {} as A const b = {} as B const array = [a, b] The array is of type (A | B)[] How can we create a utility type that ...

What sets enum with string values apart from a string type union in TypeScript?

When it comes to defining a variable with a predefined set of values in TypeScript code, there are two approaches - using an enum or using a union. For instance, imagine we have a button with various variants such as primary, secondary, and tertiary. We ...