Accessing global services in Angular 2 without the need to include them in every constructor

I am facing an issue with my three classes:

@Injectable()
export class ApiService {
  constructor(public http: Http) {}

  get(url: string) {
    return http.get(url);
  }

}

@Injectable()
export abstract class BaseService {
  constructor(protected serv: ApiService) {}  
}

@Injectable()
export class MediaService extends BaseService {

  // Why do we need this?
  constructor(s: ApiService) {
    super(s)
  }

  makeCall() {
    this.serv.get("http://www.example.com/get_data")
  }

}

While working in Angular2, I have noticed that I need to include the constructor of BaseService and MediaService, even though MediaService inherits from BaseService.

I am trying to figure out a way to inject Angular2 into the BaseService without having it in the constructor of MediaService.

Currently, all the classes are extending the BaseService and depending on the ApiService, even though they inherit from the BaseService.

Answer №1

To achieve dependency injection in a class, you must utilize the constructor. Constructors are not inherited, so it is necessary to define and implement the constructor in each subclass, passing arguments to the superclass constructor with super(arguments). The only exception to this rule is default constructors that do not require any arguments, as they are automatically generated.

Another approach is to inject the Injector and pass it to the superclass, where the superclass can then request Http from the Injector when needed. This method may be advantageous when injecting multiple services, as it allows for declaring just one constructor argument. However, in my view, this approach could make the code more difficult to understand and reason about.

Answer №2

I believe that support is not provided for this. Dependency injection in Angular2 operates based on decorators, utilizing the constructor of the associated class to determine what needs to be injected. Keep in mind that while TypeScript naturally supports classes and extends, this code is transpiled into JavaScript.

To learn more about the transpiled code, refer to this answer:

  • How to inject service to class and then extend component with it?

I hope this explanation proves beneficial, Thierry

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

Understanding the Functions of Angular Providers and Implementing Them

Just starting out with Angular and following a tutorial from this video. I decided to experiment by adding providers :[EmployeeService] to both employee-list.component.ts and empployee.component.ts within the @component section. However, this led to an err ...

Restricting a checkbox to a maximum of 5 checkmarks

In a multi-column table, each column is represented by a checkmark. I want to limit the ability to tick a checkmark to only 5 checkmarks. Here is the code that has been implemented: <tbody> <ng-container *ngFor="let col of testData" ...

Using Angular 5 with ng2-smart-table to conditionally hide or disable the actions column

I am working with a table generated by ng2-smart-table. The data in the table can be in two states: Draft and Ready. I need to implement a condition where if the data.status = 'Draft', the actions column for CRUD operations is displayed, but if t ...

Designing a TypeScript class that incorporates an interface

Struggling to grasp the correct syntax, I am looking to incorporate an interface into my project. The desired interface for implementation is as follows: interface Test { [name : string] : (source : string) => void; } My understanding is that this ...

What is the best way to retrieve the desired Angular GET format from an Express server?

As I work on developing an Express server (localhost:3000) and an Angular application to retrieve values, I have encountered an interesting issue. Despite specifying the GET header as "text/html", the result displayed in the Angular console always appears ...

Dealing with circular references in class attributes within Angular

I'm facing a challenge in Angular while trying to set up mock data. I have the following two classes: export class Company { public id: number; public name: string; public applications: Application[]; constructor(id: number, name: string, ap ...

Unable to link the second array to the angular-dual-listbox

I am struggling to connect my JSON data with the Confirmed list in an angular-dual-listbox component created by czeckd. The source part appears correctly, but the Destination list is not displaying the expected results. I have set up a live example on Sta ...

Adding dependency service to the parent class in Angular

I am working with classes parent and child. The child class is an extension of the parent class. I want to inject the injectable class service into the parent class since all instances of the child class will be using it as well. Can someone guide me on ...

Utilizing Typescript to Inject Generics and Retrieve the Name of an ES6 Module

I am currently working on developing a versatile repository using: Typescript ES6 Angular 1.x However, I am facing challenges in determining the correct way to inject the Entity and retrieve its module name. The main reason for needing the name: I adh ...

Purifying potentially harmful style value for background-image when using ngStyle with a conditional statement

I'm attempting to dynamically display a background image of a div using ngStyle. I have also set a fallback image in case the default value is null. <div class="card-img-top" [ngStyle]="{'background-image': process.thumbna ...

Combining user input with React's useState function

I have a form with three Quantity inputs. (Although more can be added dynamically, let's keep it simple for now and stick to three.) | - | - | Quantity | |---|---|----------| | - | - | 3 | | - | - | 4 | | - | - | 5 | Now, I want ...

Angular Material: The property 'openDialogs' cannot be read because it is undefined

Struggling with writing a test for a component that utilizes a MatDialog and running into errors. The error message mentioned above is causing the test to fail. Here are some additional insights on when the error occurs: at MatDialogTitle.Object.<a ...

Should I utilize peerDependencies or dependencies for Angular 2 dependencies when developing an npm package for an Angular 2 library?

When creating an npm package for Angular 2, specifically as Angular 2 services, I typically utilize peerDependencies in the following manner: "peerDependencies": { "@angular/core": "^2.0.0", "rxjs": "5.0.0-beta.12", "zone.js": "^0.6.6" } ...

Customize Monaco Editor: Implementing Read-Only Sections

I am currently working on setting up the Monaco Editor so that specific sections of the text content are read-only. Specifically, I want the first and last lines to be read-only. See example below: public something(someArgument) { // This line is read-onl ...

Constructing an Angular component with any content in the constructor can cause the entire page to malfunction

When attempting to modify the constructor of one of my Angular components, I encountered an issue where adding any code to the constructor caused the entire page to render blank. This resulted in all other components disappearing and only displaying the ba ...

Encountering a 'scheduler flush execution error' and an Uncaught TypeError due to VueJS and Axios integration

After carefully examining my code, I have pinpointed the cause of this error to the following line: treeNodes.value = documentStore.convertToTree((await axios.get('/File')).data); Initially, I receive a warning: Vue warn]: Unhandled error during ...

Unusual Behavior of Observable.concat() in Angular 4 with RxJS 5

My Angular 4 / TypeScript 2.3 service has a method called build() that throws an error if a certain property is not initialized. I am attempting to create a safer alternative called safeBuild() that will return an Observable and wait for the property to be ...

Is Angular Module Lazy Loading functioning properly in Chrome?

Is there a way to verify if the JavaScript files are lazy loaded for the currently opened module using Chrome developer tools? ...

Unable to render information within the PrimeNG tree component

I've set a goal for myself to create a treeview using the PrimeNG Tree Component. Currently, I have a small service with the following method: TypeScript: getMenuDetails(parentID: number) { let url = this.serverURL + 'api/Nodes/' + pa ...

I am unable to employ filtering in TypeScript

Hey there, I'm trying to filter some JSON data randomly by using this function, but I keep running into an error with my variable called filteredArray. The error message says "Property 'filter' does not exist on type 'Dispatch<SetSta ...