What is the best method for distributing an Angular service from a library created using ng generate library?

I'm currently facing a challenge in sharing a service from the npm package that I created using ng g library with my Angular hosting application. While I have experience in linking components and directives, I'm a bit lost when it comes to services.

Within the library, I have the following key files:

  • authentication.service.ts
  • authentication.module.ts

All of these are listed in the public-api.ts file and successfully imported into my hosting app.

authentication.service.ts: (I've experimented without using providedIn: 'root' as well)

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
...
}

authentication.module.ts:

@NgModule({
})
export class AuthenticationModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: AuthenticationModule,
      providers: [AuthenticationService]
    };
  }
}

hosting app's app.module.ts:

import { AuthenticationService } from '@custom/lib';
import { AuthenticationModule } from '@custom/lib';

export function appInitFactory(
    injector: Injector,
    authenticationService: AuthenticationService,
    configService: ConfigService
  ): any {
    return () =>
      loadConfig(configService, authenticationService)
        .then(() => checkLogIn(injector, authenticationService));
}

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AuthenticationModule.forRoot()
  ],
  providers: [
    AuthenticationService,
    {
      provide: LocationStrategy,
      useClass: HashLocationStrategy
    },
    {
      provide: APP_INITIALIZER,
      useFactory: appInitFactory,
      deps: [Injector, AuthenticationService, ConfigService],
      multi: true,
    }

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

I'm keen on injecting the AuthenticationService into the appInitFactory because this is where I load application configuration from a JSON file and perform authentication validation before the hosting app initializes.

The error message I encounter reads as follows:

core.js:15723 ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[AuthenticationService]: 
  StaticInjectorError(Platform: core)[AuthenticationService]: 
    NullInjectorError: No provider for AuthenticationService!
Error: StaticInjectorError(AppModule)[AuthenticationService]: 
  StaticInjectorError(Platform: core)[AuthenticationService]: 
    NullInjectorError: No provider for AuthenticationService!
    at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get

If anyone has insights on what might be causing this error, your assistance is greatly appreciated.

Answer №1

It's unnecessary to include the

@Injectable({
  providedIn: 'root'
})

declaration. You can simply use

@Injectable()

since you are already providing it in the forRoot method.

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

Removing the final element within a nested array: a step-by-step guide

let originalArray=[ [ "Test1", "4", "160496" ], [ "Test2", "6", "38355" ], [ "Test3", "1", "1221781" ], [ " ...

Solving TypeScript Error in React for State Destructuring

Recently, I've been working on creating a React component for AutoComplete based on a tutorial. In my development process, I am using Typescript. However, I encountered an issue while trying to destructure the state within the render suggestions metho ...

Troubleshooting Cross-Origin Resource Sharing (CORS) issues with Font Awesome font in

For a while now, I've been using Angular and Material without any issues. However, recently I encountered a problem that has me puzzled. When running my Angular app from IntelliJ, an error message appeared in the console. The error stated: Access to ...

Finding the root directory of a Node project when using a globally installed Node package

I've developed a tool that automatically generates source code files for projects in the current working directory. I want to install this tool globally using npm -g mypackage and store its configuration in a .config.json file within each project&apos ...

What is the best way to set up a sidenav with router-outlet and a distinct login page with router-outlet?

My goal is to create an application with a login page that, once the user logs in, displays a navbar, toolbar, and sidenav with a router-outlet. In my app.component.html, I have set it up like this: <div *ngIf="isAuthenticated"> <app- ...

Expanding a Zod object by merging it with a different object and selecting specific entries

Utilizing Zod, a TypeScript schema validation library, to validate objects within my application has led me to encounter a specific scenario. I find myself in need of validating an object with nested properties and extending it with another object while se ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

Guide on creating a similar encryption function in Node JS that is equivalent to the one written in Java

In Java, there is a function used for encryption. public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new Buffer ...

"Exploring the insertion of a line break within the modal body of an Angular application

Is it possible to create a modal for error messages with multilined body messages without altering the modal template? Any assistance would be greatly appreciated. <div class="modal-body" > <p *ngIf="!_isTranslatable">{{_modalBody}}</p&g ...

Monitor changes in input display within ngIf statements

Within my code, I am utilizing an input element within a conditional statement of *ngIf: <div *ngIf='display'> <input number="number" /> </div> My goal is to be able to detect the visibility state of the input element insi ...

Adding a declaration file to a package that relies on an external declaration file can be achieved by following these

In the process of developing a library that relies on another package lacking a declaration file in its npm package, I have successfully installed the necessary declaration file with typings. Everything seems to be working well. Yet, the question remains: ...

Enhancing User Experience through 'Remember Me' Feature in Angular App

I need assistance with adding the Remember Me functionality to a login form in an Angular application. Could someone please provide guidance on how to achieve this? Your help would be highly appreciated! Thank you in advance! Below is my login.ts file: ngO ...

Tips for managing the data type of a bound value through ngModel: preventing number distortion to string

I posted a query and managed to solve it. However, I observed that even though the provided data consists of objects defined like this: export interface GisPoint { e: number; n: number; } when a user inputs a value, the original content changes from { e: ...

Error in Angular nested form: Unable to access property 'length' of null object

I have created a nested form with various form controls: this.newRequest = this._fb.group({ requestType: [], tripType: [], feeders: [''], directFlight: [], departure: [''], arrival: [''], depDate: ...

Mysterious Error Retrieving /v2/me Endpoint from LinkedIn in Angular 11

My goal is to retrieve the r_liteprofile from LinkedIn using the Oauth2 3-legged flow. While it works perfectly in Postman, I keep encountering an 'Unknown Error' in Angular 11: Here's a snippet of the code: params = new HttpParams() .set(& ...

"Learn how to dynamically change the color of a button in Angular after it has been clicked

Can someone assist me in changing the button color to red after it has been clicked? I am looking for guidance on how to achieve this. The current code snippet is as follows: <td> <button mat-icon-button color="primary"> <m ...

The animation of the splash screen in Angular is quite jarring and lacks fluidity

I am experiencing some issues with my angular splash screen animation. It works perfectly when there is no activity in the background, but when I simulate a real-life application scenario, the animation becomes stuttered, choppy, or sometimes does not anim ...

Whenever I try to log in on Angular 11, I encounter the HttpErrorResponse error with a status code of

I have encountered an error and cannot seem to find a solution. Here is the code snippet: login(signInRequestPayload: SignInRequestPayload): Observable<boolean> { return this.httpClient.post<SignInResponse>( '/api/v1/registration/login&apo ...

Error occurs when attempting to instantiate a class with parameters that do not match any available constructor signatures

I am attempting to encapsulate each instance of router.navigateByUrl within a class function, with the intention of calling that function in the appropriate context. However, I am encountering an error that states 'Supplied parameters do not match any ...

Organizing Angular models and interfaces

The Angular styleguide provides best practices for using classes and interfaces in applications, but it does not offer guidance on organizing interfaces and model classes. One common question that arises is: what are the best practices for organizing file ...