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

Is there a way to verify an if-else statement in the ngStyle background property with Angular 7?

I have a collection of cards that need to be shown in a component. Each card contains a cover-image with an URL fetched from the server. In my component.html, I am using ngFor as follows: <div [style.background-image]="'url('+row.companyId?.c ...

Angular: Implementing default nested routes

I am currently facing a challenge with routing in my Angular application. I have set up a page within a router-output on the route /products. This page contains another router-output which will display one of two possible children routes (/products/profess ...

Can you advise on how to generate a key to access an environment.ts value within a *ngFor loop? Specifically, I am trying to locate keys that follow the pattern 'environment.{{region}}_couche_url' within the loop

I currently have a block of HTML code that is repeated multiple times. <!-- Metropolitan Map --> <div> <app-map [name] = "(( environment.metropole_name ))" [layer_url] = "(( environment.metropole_layer_url ))" ...

Unable to establish a connection to 'X' as it is not recognized as a valid property

Trying to implement a Tinder-like swiping feature in my Angular project, but encountering an error stating that the property parentSubject is not recognized within my card component. Despite using the @Input() annotation for the property, it still fails to ...

What are some effective methods for troubleshooting Vue.js computed properties and templates?

I am facing challenges with debugging in Vue.js, especially when it comes to debugging computed properties or data values in templates. Currently, I am using the IIFE method for debugging as shown in : <h2 dir="auto"> {{(function(){debugger;let ...

Angular 6 ActivatedRoute Parameters

I'm having trouble retrieving the data of each record using ActivatedRoute. I've been able to get the ID for each one, but I can't seem to access the other data. Any suggestions? Check out my stackblitz example: https://stackblitz.com/edit/ ...

Error: Module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef' does not export 'ProSidebar' as requested

Using the pro-side-bar library in React is causing an issue for me. When I run the code, the console shows the following error using the dev tools: Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef& ...

Having trouble setting State in React with Typescript?

I have encountered an issue with merging strings in an array. Despite successfully joining two strings and logging the result using console.log('Dates: ' + mergedActions), the merged string doesn't seem to be set in this.state.MergedAllActio ...

Updates made to Angular components do not get transpiled to JavaScript

Embarking on my first ASP.NET Core application journey with Angular 2! User access is a top priority for the application. Facing the absence of an Angular template in Visual Studio 2017, I opted to use Powershell and Yoman to generate an Angular project s ...

Expanding constructor in TypeScript

Can the process described in this answer be achieved using Typescript? Subclassing a Java Builder class This is the base class I have implemented so far: export class ProfileBuilder { name: string; withName(value: string): ProfileBuilder { ...

Error TS2339: The 'phoneType' property cannot be found on the 'Object' data type

Below is the declaration of an object: export class Card { private _phones:Object[] get phones(): Object[]{ if(this._phones === undefined) this._phones = [] return this._phones } set phones(val:Object[]){ ...

How can one ensure that the element declared in the "let" clause is displayed in an HTML Angular template?

I am working on a component that can render a mat-table. Each cell can have a specified value, or if it is present, the component calls an ngTemplateOutlet and passes it a rendering function obtained from the calling object. export interface ColumnConfig { ...

In Angular 12, encountering the error "Unable to bind to 'formGroup' as it is not a recognized property of 'form'" is not uncommon

Encountering a problem that seems to have been addressed previously. Error: Can't bind to 'formGroup' since it isn't a known property of 'form'. I followed the steps by importing ReactiveFormsModule and FormsModule in the req ...

Secure mustache templates for data validation

Is there a method to achieve the following?: my-custom-template.mstach Hello {{name}}! script.js import { readFileSync, writeFileSync } from 'fs'; import * as Mustache from 'mustache'; export interface Person { name: string; } ...

Difficulty Determining Literal Types that Expand a Union of Basic Data Types

Below are the components and function I am working with: interface ILabel<T> { readonly label: string; readonly key: T } interface IProps<T> { readonly labels: Array<ILabel<T>>; readonly defaultValue: T; readonly onChange ...

Chakra UI - The "Open Modal" button is disabled from being clicked repeatedly

Encountering an issue with Chakra UI modal dialog in Next.js. Attempting to utilize the code below in pages/index.tsx for displaying a modal dialog. import type { NextPage } from "next"; import { Modal, ModalOverlay, ModalContent, Moda ...

Invoke a method in a child component from its parent component

Is there a way to trigger a function on a child component from the parent component? In my scenario, I have a ModalComponent (parent) and a MessageComponent (child), and I need them to communicate. In Angular 1, this was achievable through a shared service ...

Using the Angular JSON pipe with angular-datatables

I am currently utilizing angular-datatables to exhibit NoSQL de-normalized data in a grid format for visualization purposes. Within my dataset, I have several intricate nested JSON objects and I intend to showcase a specific cell with formatted JSON using ...

The modal popup feature is dysfunctional within the hierarchical component structure of angular-bootstrap-md

In my project, there is a structured hierarchy of components that includes: Agent task-list (utilizing the shared task-list-table component) task-type (as a separate component) preview-task (a modal component) agent.component.html (where task-type, ta ...

Why am I getting a null value for my Array when I should be expecting an Object instead?

I have been attempting to create an Array that contains objects for a project, but I keep encountering an error message stating: "this.allgmArray is undefined". However, it is not actually undefined: allgmArray: DialogBook[]; [...] load(){ for(var i ...