angular dependency injection chain fails to function after relocation to a library

Within the angular application called "app-standalone," I successfully utilized the injectables CoreService, OuterService, and OutmostService in the AppComponent. Here is the link to the corresponding code: https://github.com/moky80/angular-injectable-chain/blob/master/app-standalone/src/app/app.component.ts.

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class CoreService {
  constructor() { console.log("Initialized Core");
} }
@Injectable({ providedIn: 'root' })
export class OuterService {
  constructor(private core: CoreService) {
    console.log("Initialized Outer");
}}
@Injectable({   providedIn: 'root' })
export class OutmostService { constructor(private outer: OuterService) {
    console.log("Initialized Outmost");
}}
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent {
  title = 'app-standalone';
  constructor(private outmost: OutmostService){
    console.log("Initialized AppComponent");
  }
}

In the next phase, I transferred CoreService and OuterService to an Angular library named “lib-core.” The relevant code can be found here: https://github.com/moky80/angular-injectable-chain/blob/master/lib-core/projects/lib-core/src/lib/lib-core.service.ts.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CoreService {
  constructor() {
    console.log("Initialized Core");
  }
}

@Injectable({
  providedIn: 'root'
})
export class OuterService {
  constructor(private core: CoreService) {
    console.log("Initialized Outer");
  }
}

Subsequently, I developed a new application called “app-uses-lib-core,” which incorporates the lib-core functionality: https://github.com/moky80/angular-injectable-chain/blob/master/app-uses-lib-core/src/app/app.component.ts.

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { Injectable } from '@angular/core';
import { OuterService } from 'lib-core';

@Injectable({   providedIn: 'root' })
export class OutmostService { constructor(private outer: OuterService) {
    console.log("Initialized Outmost");
}}
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent {
  title = 'app-uses-lib-core';
  constructor(private outmost: OutmostService){
    console.log("Initialized AppComponent");
  }
}

The issue arose when running "app-uses-lib-core," resulting in the error message "NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with runInInjectionContext."

I am puzzled as to why moving CoreService and OuterService to lib-core caused this problem. If anyone has insights into what might be wrong with "lib-core" and "app-uses-lib-core" and how to rectify it using Angular 7, please share your thoughts.

Answer №1

Thanks to a helpful hint from @Naren Murali and the useful link shared here

https://i.sstatic.net/C0xhubrk.png

Solution to the problem was setting

projects.projectName.architect.build.options.preserveSymlinks
to true in angular.json

This issue was also discussed on: this thread

Answer №2

The issue lies in your development process, where implementing symlinks to connect the library with the application is necessary.

I faced no problems when I followed the standard method of configuring the package using a local file.

"lib-core": "file:../lib-core/dist/lib-core/lib-core-0.0.0-watch+1726241313493.tgz",

To learn more about how to develop locally using libraries and applications, refer to the following articles:

Guide on Developing Angular Libraries Locally

Creating and Using an Angular 14 Library Locally for Development and Publishing to npm


I have made some minor corrections to your library, feel free to check it out.

Visit Github Repo

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

How can we update the form builder or form group in Angular 2 when making changes to the existing data in a table? I'm a bit confused on how to implement router

<tr *ngFor="let row of categories "> <td>{{row.categoryName}}</td> <td>{{row.visible}}</td> <td>{{row.instanceNumber}}</td> <td> <a class="btn btn-info btn-fill " [routerLink]="['/con ...

The modal window will only close when I click on the input field and then press the Escape button

Is there a way to close my modal window on Escape without having to click inside the modal first? closeModalEsc(e) { if (e.keyCode === 27) { return this.props.closeModal(); } } render() { const {modal, close ...

Issue: The Clerk authentication function was invoked, but Clerk was unable to detect the usage of clerkMiddleware() (or the outdated authMiddleware())

I've been following a YouTube tutorial (https://youtu.be/zgGhzuBZOQg) to create a next.js project with Clerk. However, I keep encountering error messages in the terminal every time the site loads: Error: Clerk: auth() was called but Clerk can't ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

How to Extract a Variable from an Array in Angular 2 (pertaining to front-end development in html and component.ts)

Below is the code snippet illustrating my issue. I have an array named 'mydmcanotice' with four attributes enclosed in {{}} brackets. Each dmca within mydmcanotice has an associated button. My goal is to display dmca.nameofsong in a textarea when ...

Changing the value of a property in an object based on the object's attribute in JavaScript

I have a JSON data set like this: inputData = [ { id : 179849, name : alex , lastname: sanchez}, { id : 788539, name : Paul, lastname: bearer}, { id : 282169, name : Jean, lastname: nobel}, ... { id : 632785, name : Maria, lastname: parak} ] I am looking ...

Using NativeScript and Angular for Code Sharing Application

Recently, I followed the steps outlined in the Nativescript documentation for creating a new code sharing project here, and decided to incorporate sass into my project. I attempted both methods - one with the Nativescript theme applied, and the other witho ...

How do I customize the alert in ion-select using IONIC ANGULAR?

How can I create a select element like this: https://i.sstatic.net/2LJA0.png Is it possible to customize the selected item? https://i.sstatic.net/oIT6a.png I'm new to working with Ionic. I've tried using custom properties, but they don't ...

Incorporating Angular 6 and NodeJS 8.4 with the MEAN stack, I aim to display the current status of all identifiers stored in MongoDB directly onto the browser

After successfully storing the list of objects in MongoDB, I have implemented a functionality to display all items on the browser. When the inventory button is clicked, the routerlink is used to fetch the availability and list them accordingly. Now, I am ...

Increasing the font size of the mdToolTip in Angular2 Materials

Recently, I've been trying to adjust the font size in mdToolTip. While looking through the pre-themes CSS, I came across this class: .mat-tooltip { background: red; font-size: 50px; } However, it seems to be ignoring the font-size syntax. Can any ...

An error occurred while uploading a file in the StaticInjectorError of the AppModule related to the HttpHandler and Injector

Hey there! I'm currently working on a project using Angular 9 and Angular Material. I'm trying to implement the mat-file-upload feature, but when I run the app, I keep getting this error message: "StaticInjectorError(AppModule)[HttpHandler -> ...

The 'connectedCallback' property is not found in the 'HTMLElement' type

After taking a break from my project for a year, I came back to find that certain code which used to work is now causing issues: interface HTMLElement { attributeChangedCallback(attributeName: string, oldValue: string, newValue: string): void; con ...

Encountering a surprise focus error in ngui-auto-complete within Angular

In the process of developing a web application, I have encountered an unexpected focus issue with the ngui-auto-complete on one of the pages. Despite not setting any focus event for this particular element, it remains focused once the content is initialize ...

eslint rule prohibiting directly checking numbers

Does eslint have a rule that flags an error for the code snippet below: function parseNumber(numberToCheck: number | undefined) { // I want an error here: !0 is true, so we will get "no number" here if (!numberToCheck) { return "no n ...

Retrieving Information from an Angular 2 Component

Struggling to figure this out, I am attempting to dynamically add user video data that includes a video URL. My goal is to access the data from the component so I can use it in my HTML. I've attempted the following approach. app.component.ts import ...

Disable TS4023 error in TypeScript: Unable to name external module "xyz"

//custom-slice.js import { createCustomSlice } from '@my/data-toolkit'; /* ***********************For Managing all the divisions data****************************** */ export const divisionDataSlice = createCustomSlice({ name: 'divisionda ...

Is it considered bad form to utilize nearly identical for loops in two separate instances within Angular 6?

I am working on creating two lists for a roster. The first list will display the current members of this year, while the second list will show if individuals have been excused for this year. After analyzing my code, I realized that I am using two identic ...

Tips for creating a versatile object combine function in TypeScript

Is there a way to create a generic function in TypeScript 4.4+ that is equivalent to {...a,...b} operation? Both a and b are records, but their types are unknown in advance. I want to define a generic type that enforces arbitrary functions to perform the { ...

Error encountered in TypeScript exclusively when implementing GetStaticProps function within a Next.js component and using the getStaticProps method

I'm encountering a challenge with TypeScript as I try to implement the type GetStaticProps in my code. Surprisingly, everything runs smoothly without any issues when this type is not used. The error message reported by TypeScript has left me puzzled. ...

`How can I enhance the appearance of an Angular 4 component using an attribute?`

There is a component where I need to pass specific data to the child components within an ngFor loop using attributes. Depending on the attribute, I want to style these child components accordingly. Code testimonials.component.html - (Parent component) ...