Angular service from an external package is experiencing issues with dependency injection where the HttpClient is returning

Imagine you are working with Angular and have the following custom libraries:

The first library is a base service library:

// base.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export abstract class BaseService {
  constructor(private httpClient: HttpClient) {}

  protected request(): Observable<any> {
    return this.httpClient.request('GET', 'http://127.0.0.1:3100/CRM/v1/customers');
  }
}

The second custom library is:

// test.service.ts

import { Injectable } from '@angular/core';
import { BaseService } from '@company/data-access-base';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export abstract class TestService extends BaseService {
  testRequest(): Observable<any> {
    return this.request();
  }
}

Then you decide to incorporate the TestService into your application.

Assuming you have already imported HttpClientModule in the app.module.ts file of your application, you proceed to inject the TestService and utilize it in the following manner:

import { Component, OnInit } from '@angular/core';
import { TestService } from '@company/data-access-test';

@Component({
  selector: 'comp-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  constructor(private testService: TestService) {}

  ngOnInit() {
    this.testService.testRequest().subscribe((r) => console.log('Test ok', r))
  }
}

However, upon testing the functionality, an error is encountered in the console:

core.js:4610 ERROR TypeError: Cannot read property 'request' of undefined
    at TestService.request (company-data-access-base.js:42)
    at TestService.testRequest (company-data-access-crm.js:7)
    at HomeComponent.ngOnInit (home.component.ts:13)
    at callHook (core.js:3405)
    ...

The question then arises: How can I ensure that HttpClient is properly injected into the BaseService?

Answer №1

It appears that the injected service in the application is named TestService, and this is the service that Angular (and most likely any other DI system in different frameworks) will handle.

The solution is quite simple: just add a constructor to every service and invoke the super(httpService).

// test.service.ts
import { Injectable } from '@angular/core';
import { BaseService } from '@company/data-access-base';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export abstract class TestService extends BaseService {

  // the missing piece
  constructor(protected httpClient: HttpClient) {
    super(httpClient);
  }

  testRequest(): Observable<any> {
    return this.request();
  }
}

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

Encountering an Eslint issue upon trying to implement the rule @typescript-eslint/interface-name-prefix

After implementing the rule, "@typescript-eslint/interface-name-prefix": [ "error", { "prefixWithI": "always" }] The system displays this error message: Rule definition for '@typescript-eslint/interface-name-p ...

Ways to transfer certain characteristics of an Observable to a different Observable by leveraging RxJS operators

I am working with two Observables, employee$ and personalInformation$. The personalInformation$ Observable is a subset of employee$ and I need to map the matching properties from employee$ to personalInformation$. Although both observables have many more f ...

Angular 6 - Navigation drawer covers up main content when using ngx-translate

I am experiencing difficulties with the ngx-translate library because translated texts are displayed in the selected language AFTER the main component is shown. My main component structure looks like this: <app-header></app-header> <mat-si ...

Is it possible to dynamically assign class properties from an array in JavaScript/TypeScript?

Greetings for the assistance in advance. Currently, I am working with TypeScript, but I believe any JS solution will suffice. I aim to create something akin to the following: class ExcelData { 'Id 1': items[0].id, 'Quantity 1': item ...

Guide to integrating Inversify with Mocha

In my TypeScript Node.js application, I am implementing Dependency Injection using Inversify. The functionality works perfectly during the app's execution. However, I encountered an issue with the @injectable() annotation when running tests. An error ...

Customize behavior by dragging and dropping

I am working on implementing a particular behavior in Angular 8, using the Angular CDK Drag-Drop module. I have encountered some issues with it. Here are the code snippets: $('.dragger').draggable({ revert: "invalid", helper: function () ...

personalize the text in fusioncharts' chart legend item

Is there a way to modify the legend display for the doughnut2D chart to appear as a rectangle with separate rows for the value and label, along with icons as shown in the screenshot link? If you have any code examples or implementations for this, it would ...

What is the correct data type for the vuex store that is passed to the vuex plugin when it is being initialized?

Here is how the store initialization process is currently being implemented: /* Logic */ import Vue from 'vue' import Vuex, { StoreOptions } from 'vuex' Vue.use(Vuex) const DataManager = new UserDataManager() type RootStateType = { ...

Restrict the output to two decimal places using a straightforward pipe symbol

I came across a method that restricts a number to 2 decimal places and also formats it as a currency - for example, £2.55. {{ number | currency : 'GBP' : true : '1.2-2'}} Is there a straightforward pipe that achieves the same result ...

When working with TypeScript, it's important to note that an implicit 'any' type may occur when trying to use an expression of type 'string' to index a specific type

Currently, I'm attempting to transfer a custom hook used in Vue for handling i18n from JavaScript to TypeScript. However, I am encountering a persistent error message: An element is implicitly assigned the type 'any' due to an expression o ...

"Amplify your Angular skills by mastering the process of looping through an array

I'm attempting to post my second array and obtain the id of item() in order to create an item set with that ID. However, I am struggling to achieve this. Here is what I have tried so far, but it does not seem to work: postArray(){ console.log ...

Angular: Excessive mat-menu items causing overflow beyond the page's boundaries

Within my mat-menu, there is a div for each mat-menu item. The number of items varies depending on the data retrieved. However, I noticed that when there are more items than can fit in the menu, it extends beyond the boundaries of the mat-menu instead of ...

Using ng-mocks for MockBuilder and MockRender while injecting a real service

I am currently faced with the challenge of independently testing a child component that relies on a FormGroup as input, serving as a section within the parent form. Our team utilizes an in-house framework that streamlines the form-building process through ...

Encountering an ECONNREFUSED error upon upgrading from Next.js 12 to 13

After upgrading from Nextjs 12 to 13, I am experiencing issues where every time I try to run the application, I encounter ECONNREFUSED to my local host but the port seems to keep changing. This results in the application not rendering properly. > <a ...

Deleting items from a JavaScript object array in Angular using TypeScript can be achieved by using various methods and

Here is the structure of my object array: 0: {Name: "Albert", Id: 32} 1: {Name: "George", Id: 34} 2: {Name: "Jane", Id: 35} Although the request is successful, the array remains unchanged. However, upon refreshing the app, the item (student) is deleted. ...

Ways to effectively manage the cell component's behavior during the onmouse event

Here lies my source code. At this moment, the onmouseover event handler can be found in app.component.ts. Would it be feasible to transfer the onmouseover event handler to shift-cell.component.ts? If not, how does the handler determine which cell has the ...

How can the adapter pattern be implemented in Angular when dealing with an HTTP response containing an array of objects?

Using the adapter pattern in Angular, I have successfully adapted Http response to an 'Invoice' object. However, I am facing a challenge when one of the properties inside the 'Item' is an array. In this scenario, the 'items' ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

Tips for organizing an NPM package containing essential tools

Currently facing the challenge of creating an NPM package to streamline common functionality across multiple frontend projects in our organization. However, I am uncertain about the correct approach. Our projects are built using Typescript, and it seems th ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...