Discover the best practices for implementing services within the import decorator of an angular module configuration

Is there a way to access a service inside the load module in Angular, especially when the module is loaded from a decorator and the service is not yet DI?

You can refer to this answer for an example.

For instance, if the method in the service returns an Observable, the config would look like this:

export interface TranslateConfig {
  someProp?: string;
  anotherProp?: string;
  observableProp?: Observable<string>
}

When loading the module in app.module.ts:

@NgModule({
  imports: [
    TranslateModule.forRoot({
      someProp: someValue,
      anotherProp: anotherValue,
      observableProp: (method from service)
    })
  ]
})
export class AppModule{
  ...
}

The goal is to make use of the service within the decorator.

Answer №1

This problem has been resolved. It is not possible to use a service inside a decorator.

To fix this issue, you should create a new service inside ConfigurableModule.

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

  constructor() { }

  private authFunction: Observable<string>;
}

In your app.module.ts

@NgModule({
  ...
  imports: [
    ConfigurableModule.forRoot({
      YOUR CONFIG HERE
    }),
  ],
...
})
export class AppModule {
  constructor(
    private configurableModuleAuthService: ConfigurableModuleAuthService
  ) {
    configurableModuleAuthService.authFunction = of("YOUR AUTHENTICATION OBSERVABLE METHOD HERE");
  }
}

To utilize this service within ConfigurableModule, the process is the same as with a regular DI service

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

Using HTML and JavaScript to automatically update one input date based on changes made to another

Currently, I am developing an Angular application and encountered a challenge with two date input fields: <div class="col-lg-3"> <div> {{ dataInizioLabel }} </div> <input required type="datetime-local" ...

Encountering a "No overload matches this call" error while using React, Typescript, and d3js

Encountered an error in Typescript while using the scaleLinear() function from d3js. Seeking assistance in resolving this issue. The code is in React and utilizes typescript. Below is the source code: import React, { useRef, useState, useEffect } from &apo ...

The issue of Angular 15 Childcomponent failing to refresh the user interface despite input modifications

Within this component, I have two child components: <span>Timings:</span> <sir-project-fasetiming [faseTiming]="projectTiming.timingInitiatie" (faseTimingChanged)="faseTimingChanged($event, 'timingInitiatie')"&g ...

Is Typescript capable of identifying void functions automatically?

Being new to Typescript and programming in general. Instead of using: function greet(greeting: string): void; Can I simplify it like this? Is there any type inference? function greet(greeting: string); ...

Searching for data based on specific keywords in Angular 2, rather than using a wildcard search, can be done by utilizing the key-in

My dropdown contains 100 values, and I am currently able to search for these values based on key input using wild search. However, I would like the dropdown to display values based on the specific alphabet that I enter first. HTML: <div class="col- ...

Is there a way for me to retrieve the bodyHeight attribute of ag-grid using public variables or data?

Working on a project using ag-grid community react. The main feature is a scrollable section filled with data, which can range from one piece to millions of pieces. I'm also incorporating a footer component for the grid that needs to adjust its height ...

ngx-toastr memory leak prevention

Currently, I am dealing with a memory leak problem within my application and I've noticed that there are multiple occurrences of the following code scattered throughout the project: this.toastr.success("message sent!", "", { timeO ...

How to configure mat-sort-header in Angular Material for mat-table

My current table is created using Angular Material: <mat-table *ngIf="!waiting" class="table-general table-summary" #table [dataSource]="dataSource" matSort> <mat-header-row class="header_row" *matHeaderRowDef="headerKeys"></mat-header ...

Guide on building an npm package that seamlessly allows for installation both locally and globally (-g) using webpack and typescript

As I work on developing an npm package with options for both local and global (-g) installations, I find myself puzzled by the distinctions between the src and lib directories and the purpose of the bin directory. In my previous projects, I typically util ...

Create distinct projects for WebApi and Angular to keep them separate

Currently, I am working on a project that involves webApi and Angular apps combined in one project by default from Visual Studio. However, I want to separate them into two distinct projects. To achieve this, I removed all the SPA-related code from my StarU ...

Route protection is ineffective when dealing with two observables simultaneously

After writing the route guard as shown below, I encountered an issue with the else statement that was not returning a result, even though it should have. Surprisingly, there were no errors either. this.hotelSettingsService.get().pipe(map(res => { ...

Tips and techniques for updating the form value in Angular 4 Material while maintaining binding characteristics

import {Component,ViewChild} from '@angular/core'; import {NgForm} from '@angular/forms' @Component({ selector: 'checkbox-configurable-example', templateUrl: 'checkbox-configurable-example.html', styleUrls: [& ...

Typescript: The type 'Observable<{}>' cannot be assigned to the type 'Observable'

I'm encountering an issue with the Observable type, any thoughts on how to resolve it? import { PostModel } from '../model/postModel'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable&ap ...

React Typescript: excluding a property in a higher order component

Is it possible to write Typescript type definitions that properly expose the Props type of a component created by a HOC? I want to infer the type of props of the wrapped component and remove any properties provided by the HOC. For example, if we have a HO ...

Can you please provide an explanation on the functioning of Dependency Injection in Nestjs?

I have been delving into Nest.js and incorporating it into my project structure. Additionally, I have integrated TypeORM into the mix. The concept of Dependency Injection in Nest.js has me feeling a bit perplexed. Project Structure |-APP_MODULE |-app.co ...

What is the best approach for unit testing canActivate in Angular?

Is there a way to properly test the canActivate function in Angular that returns a function which ultimately provides a boolean value? I attempted to create instances of ActivatedRouteSnapshot and RouterStateSnapshot, and then pass them into the canActiva ...

Why is it necessary to merge an interface with a function when using the new keyword?

Assuming that the setting noImplicityAny is enabled. Consider the following: function Bar() { this.f = 100; } The following code snippet will not function as expected: let x = new Bar(); An error message will be displayed: 'new' expre ...

`Mapping child routes in Angular using basic components`

I am encountering an issue with Angular 8 routes. The problem lies in the child routes not functioning properly. Here are my defined routes: const routes: Routes = [ { path: 'admin', component: MainComponent, children: [ { path: &apo ...

When the page hosted on Vercel is reloaded, `getStaticProps` does not function as expected

I'm currently working on a nextjs project and running into an issue where one of the pages returns a 404 error when it's reloaded. Within the page directory, I am using getStaticProps. pages - blogs.tsx - blog/[slug].tsx - index.tsx ...

Integrating Typescript into function parameters

I am attempting to make my function flexible by allowing it to accept either a string or a custom type onPress: (value: string | CustomType)=>void But when I try to assign a string or CustomType, the compiler gives an error saying is not assignable to ...