Using an Angular library module to inject the same service instance of an abstract class

Currently, I am in the process of developing a library and sample application using Angular 11. One specific requirement is to enable the consuming application to inject an implementation of a base class into the library. Within the library, I have already established default logic. In order to define a provider in the consuming app, I have structured it as follows:

// app.module.ts within the main application
providers: [
  {
    provide: 'MyServiceBase',
    useClass: DefaultMyService
  }
]

The base class itself is defined in the Library like so:

export abstract class MyServiceBase{
   abstract myFunction();
}

Furthermore, the default logic is implemented within the library as well:

@Injectable({
    providedIn: 'root',
})
export class DefaultMyService extends MyServiceBase {
...
}

To make use of this service within a component in the library, I inject it accordingly:

constructor(@Inject('MyServiceBase') private myService: MyServiceBase) {
...
}

However, a challenge arises when I notice that the instance of DefaultMyService injected into the consuming app differs from that in the library. While debugging the application, I observe that the code utilized in the consuming app refers to JavaScript exported by the library, whereas the code in the library itself is actually TypeScript.

I am curious if there exists a solution to ensure that the same instance is injected into both the library and consuming app?

Answer №1

I discovered the root cause of the issue after realizing that I had overlooked how the service in my library was initialized. It should not have been assigned the Inject token, as it was not meant to be dependency injected. Instead, an instance of the MyServiceBase class was being passed by the initializing class. The class responsible for initializing that object was using dependency injection without utilizing the token. By making the necessary changes to use the token, the issue was resolved.

Update -

In my particular scenario, I needed a component to have its own instance of a class (referred to as myNonDepInjectObj) to maintain separate state for each instance of the component on the page. Despite this requirement, I still wanted to incorporate a service that was dependency injected into that object. Here is the corrected code snippet which implements the token:

export class MyComponent implements OnInit {
  constructor(@Inject('MyBaseService') myService: MyBaseService) {
    const myNonDepInjectedObj = new MyObj(myService);
  }
}

Subsequently, here is the revised class definition for the obj class:

export class MyObj {
  constructor(myService: MyBaseService){
  }
}

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 there a way to locate a model using a value within a OneToMany connection?

I am trying to develop a function to retrieve a user model based on a specific value within a OneToMany relationship. Below is the function in question: async getUserViaPlatform(provider: string, id: string) { return await this.webUserRepository. ...

Substitute Customized Interface Type Identifier

I am working on creating a versatile function interface for functor map while respecting the provided interface. In the code snippet below, my goal is to ensure that the value of mb is of type Maybe<number>, rather than the actual type Functor<num ...

Modifying Font Style in Angular 4 Material

Is there a way to change the font in Angular 4 Material material.angular.io using the styles file in .CSS format instead of SASS? While the documentation offers an example for SASS at: https://github.com/angular/material2/blob/master/guides/typography.md ...

What are the best methods for querying and updating a self-relation in Prisma?

I recently obtained some self-relation tables directly from a specific Prisma example. model User { id Int @id @default(autoincrement()) name String? followedBy Follows[] @relation("follower") following Follows[] @rel ...

What is the best way to limit a property and template literal variable to identical values?

Instead of giving a title, I find it easier to demonstrate what I need: type Foo = "bar" | "baz"; interface Consistency { foo: Foo; fooTemplate: `${Foo} in a template`; } // This should compile (and it does) const valid1: Cons ...

Creating uniform-sized cards with CSS and Bootstrap

Is there a way to ensure consistent card size across all lines? I've noticed that the cards in the second line are taller. Can we base the height of all cards on this? https://i.sstatic.net/KgZwu.png Below is the HTML code: <div class="row"&g ...

HTML element within a cell of an Angular material table

Can someone assist me with a problem I am facing? I have a MatTable (Angular Material) with multiple dynamic columns using MatTableDataSource. One of the columns needs to display information from another application. Here is what I want to achieve: If ...

Why am I not receiving recommendations for the data types of a function parameter when there are multiple variations available?

I'm currently navigating a JavaScript codebase that utilizes Sequelize models with documented types specified in TypeScript declaration files (.d.ts). Within my code, I am utilizing model.update() to modify certain properties on the object: To replic ...

Why do my messages from BehaviorSubject get duplicated every time a new message is received?

Currently, I am using BehaviorSubject to receive data and also utilizing websockets, although the websocket functionality is not relevant at this moment. The main issue I am facing is why I keep receiving duplicated messages from BehaviorSubject. When exa ...

The functionality of changing the source to the "docs" folder is not supported

I'm currently working through a tutorial on deploying to GitHub Pages. You can find the tutorial here. Based on my understanding of the following command: ng build --prod --output-path docs --base-href /<project_name>/ I am using the Angular ...

Having trouble getting the NextJS custom 404 page to display?

I've located the 404.tsx file in the apps/specificapp/pages/ directory, yet NextJS continues to show the default pre-generated 404 page. Could there be a misunderstanding on my part regarding the documentation, or is there some obstacle preventing me ...

Seamless animation with Angular 4

I'm working on creating a dynamic Homepage in Angular 4 with various cards such as stats, charts, etc., all enhanced with animations. One interesting feature I've implemented is the ability to toggle chart cards to expand to full screen by clicki ...

Leverage the Node Short ID library in conjunction with Angular 6 using TypeScript

I attempted to utilize the node module within an Angular 6 typescript environment. Step one: npm i shortid Within my TypeScript class: import { shortid } from 'shortid'; let Uid = shortid.generate(); However, I encountered an error stating ...

Iterate through a collection of objects and organize the data in a specific way

Within the data structure of my API response, I am attempting to iterate through an array of objects under the items key. Each value inside these objects needs to be formatted based on the corresponding format type specified in the header key. To assist wi ...

Is there a way to upgrade Angular from version 15 to 16 without encountering issues with ESBuild getting blocked and causing the update to fail?

I have been attempting to upgrade Angular from version 15 to version 16. However, when I execute the command ng update @angular/core@16 @angular/cli@16, it initiates the update process but at a certain point, "ESBuild.exe" is triggered and my "ThreatLocker ...

Issue encountered: Upon executing 'ng add @angular/fire', an error was detected in the node_modules/firebase/compat/index.d.ts file while attempting to launch the Angular application

Recently, I decided to integrate Firebase into my project, but encountered a persistent error after installing the firebase module 'ng add @angular/fire' and running it with 'ng serve': Error: node_modules/firebase/compat/index.d.ts:770 ...

Running lint-staged on an Angular monorepo

I am facing challenges while setting up lint-staged in my Angular monorepo workspace. Despite multiple attempts, I have been unsuccessful in making it work properly. When the command ng lint --files is executed with a changed file, an error stating that *f ...

Obtaining the host and port information from a mongoose Connection

Currently, I am utilizing mongoose v5.7.1 to connect to MongoDb in NodeJS and I need to retrieve the host and port of the Connection. However, TypeScript is throwing an error stating "Property 'host' does not exist on type 'Connection'. ...

What is the reason behind tsc (Typescript Compiler) disregarding RxJS imports?

I have successfully set up my Angular2 project using JSPM and SystemJS. I am attempting to import RxJS and a few operators in my boot.ts file, but for some reason, my import is not being transpiled into the final boot.js output. // boot.ts import {Observa ...

After pressing the login button, my intention is to transition to a different page

I am relatively new to web development and working with angular. I have a login component that, upon hitting the LOGIN button, should redirect to another component on a different page. However, currently, when I click the button, it loads the data of the o ...