abstract class initialization results in throwing an error

In my abstract class, I have defined all my http calls. However, when I try to extend this class in child services, I encounter a compile time error.

Can't resolve all parameters for MyService : (?).

baseservice.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';

export abstract class BaseService{

    constructor(private http: HttpClient){} //http undefined on compile time                            

    get(){
       return this.http.get()
    }    
}

myservice.ts

@Injectable()
export class MyService extends BaseService{

  getSource() {
    return this.get('api/Source')
  }
}

When additional injectTokens are included in the constructor of the abstract class, it results in a not defined error

constructor(private http: HttpClient, @Inject(APP_CONFIG) private appConfig: any | undefined) {}

Uncaught ReferenceError: http_1 is not defined

If Options are added, initializing the HttpClient and everything works correctly

HttpOptions = {
   headers: new HttpHeaders({
    'Authorization': `Bearer ${this.token}`
   })

What could be causing this issue and how can it be resolved while creating an instance of HttpClient without any InjectTokens or httpOtions.

Answer №1

` tag, it is important to note that when working with an abstract class that has a constructor, you must also declare the constructor in the concrete class and invoke `super()`. Take a look at the example below:
@Injectable()
export class MyService extends BaseService{

  constructor(private http: HttpClient){
    super(http);
  }

  getSource() {
    return this.get('api/Source')
  }
}

Answer №2

When working with TypeScript, it is important to ensure that metadata for dependencies like <code>http: HttpClient
is emitted at compilation time in order for them to be properly recognized as dependency injections. This can be achieved by specifying a decorator on the class containing the metadata.

In a hierarchy of classes that can be injected and have dependencies annotated with TypeScript types such as http: HttpClient, the base class must include the @Injectable() decorator:

@Injectable()
export abstract class BaseService{
    constructor(private http: HttpClient) {}                       
}

export class MyService extends BaseService {}

If a child class has its own constructor, it also requires the @Injectable() decorator:

@Injectable()
export abstract class BaseService{
    constructor(private http: HttpClient) {}                       
}

@Injectable()
export class MyService extends BaseService {
    constructor(http: HttpClient, private foo: Foo) {
        super(http);
    }                       
}

It's important to note that classes using explicit @Inject annotations do not need the @Injectable decorator, as explained in this answer on Stack Overflow: how @Injectable works.

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

Discovering how to display the hidden messages section in the absence of any ongoing chats with the help of angular2

I currently have 2 tabs set up on my page. The active messages tab is functioning perfectly without any issues. However, I am encountering an error with the closed messages tab. If there are no messages in this tab, the system displays an error message w ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

Is it possible to create CSS code in an external file instead of using a style element in Angular2?

Is there a reason why angular2 generates the style code in the head style element instead of an external file? I was hoping to bundle the style code in a bundle.css file and then link it in the HTML head. ...

What is the method for inserting a loop into a print template?

There is a print method available: printData(data): void { console.log(data); let printContents, popupWin; popupWin = window.open(); popupWin.document.write(` <html> <head> <title>Print tab</title> ...

Connecting data with Angular

Recently, as part of my learning journey with Angular, I encountered an intriguing issue. While working on my code, I noticed that the error popped up in my code editor (VSCode) but not when running the code in the browser. The dilemma stemmed from settin ...

Switching to Angular 17 has ensured that any alterations made to the dependent library are no longer impacting the

During the development and debugging of an Angular project, I am linking a library (which I have also developed) using npm link. The process involves navigating to the dist/my-lib folder in the workspace where the library is located and executing npm link, ...

Differentiating functions in Typescript through method overloading by inferring the second argument's type based on the first argument's

Looking to implement method overloading in Typescript with stricter type checking for method invocation based on different arguments. I am encountering an error: 'props' is possibly 'undefined'. This is the code that is causing the e ...

Exploring Child Elements in Angular 2 Templates

I am working on a component and I need to access some child nodes from the template. I was able to access the details div, but I'm not sure why the code is functioning as it does. Can someone please explain what the Future class does? Also, why is the ...

Understanding how to handle prop types in a React application using Typescript

My current task involves using the react-google-maps library to integrate Google Maps API into my project. The documentation specifies a certain way to set up the maps component: const GoogleMapComponent: React.ComponentClass<{}> = compose( with ...

Angular form input set to disabled mode

Visit this link for code <form class="example-form"> <mat-form-field class="example-full-width"gt; <mat-label></mat-label> <input matInput placeholder="Ex. Pizza" [disabled]="filterVal ...

"Sending the selected pass selector as a parameter to the dispatched action is causing a typing

When a selector changes its value, I want to trigger an action. To achieve this, I passed the selector with a subscription instead of passing an observable. selectedSchedulingsOnPopup$ = this.store.pipe(select(selectSchedulingsByBranch)); this.store.disp ...

EPERM: unable to perform operation, encountered lstat error during execution of ng build

Encountering an issue with my Angular 4 app when running ng build. Getting the following ERROR: EPERM: operation not permitted, lstat '<dist directory>' Any suggestions or solutions to fix this problem? Thanks in advance! ...

An issue has been detected with the width attribute in Typescript when using

I have a question regarding the TypeScript error related to the width property. I've created a component called ProgressBar where I'm using Stitches for styling. However, TypeScript is throwing an error even when I specify the type as ANY. impor ...

Include a log out option in the side menu of the ionic2 application

I am working with the sidemenu template to kick off my application. I aim to incorporate a button within the sidemenu that enables users to trigger a modal alert for confirming logout. Below is the code snippet: app.component.ts: import { Component, View ...

When utilizing the RTK Query custom hook in Typescript, an error may occur stating "Invalid hook call. Hooks can only be called inside the body of a

While delving into next.js with rtkquery and typescript, I encountered an error in the useEffect hook within GoogleMapComponent.tsx. The React site pointed out that I was violating some rules of hooks usage, but this is a functional component being used in ...

Angular 18 mysteriously generating a fake routing error, even though the routes were functioning perfectly before

Issue: I've been working on integrating a login component with Google authentication in my Angular application. The user information is retrieved upon successful authentication, a token is generated, and then sent to the backend for further processing ...

What is the best way to configure multiple routes in a Next.js API?

Currently, I am in the process of setting up my API for my Next.js app. One issue I am facing revolves around how to properly structure my API routes. Specifically, I require 3 routes - to retrieve all accounts, create a new account, and fetch a single acc ...

Indicate the location of tsconfig.json file when setting up Cypress

Having trouble integrating Cypress with Typescript? I've encountered an issue where Cypress is unable to locate the tsconfig.json file I created for it. My preference is to organize my project with a custom directory structure, keeping configuration f ...

Is it possible to include a conditional type in TypeScript using inlining?

Apologies if this question seems basic to those well-versed in typesystems. I'm puzzled by the difference in outcomes when inlining a conditional statement in TypeScript. For instance, using the Extract conditional leads to different results dependin ...

Displaying data from a service on an Ionic screen: a comprehensive guide

I've retrieved JSON data from an API: { "userGroups":[ {"title":"group 1"}, {"title":"group 2"}, {"title":"group 3"}, {"title":"group 4"} ] } Currently, I am storing this raw data in NativeStorage. // userService this.userGroup ...