How can I dynamically change and load a configuration file based on the URL parameter using Angular?

My query involves modifying the config file on pageload based on a URL parameter. I currently have implemented the following:

config-loader.service.ts

@Injectable()
export class ConfigLoaderService {     
constructor(private injector: Injector, private http?: HttpClient) { }
    
      public get router(): Router {
        return this.injector.get(Router);
     }
    
      url : string;
      link : string;
      initialize() {
        this.url = this.router.url;
        if (this.url == "/demo")
        {
          this.link = 'assets/demoConfig.json'
        }
        else {
          this.link = 'assets/config.json'
        }
        return this.http.get<ModeActivation>(this.link)
          .pipe(tap((response: ModeActivation) => {

app.module.ts

  providers: [DemandeClass,
    ConfigLoaderService,
    {
      provide: APP_INITIALIZER,
      deps: [
        ConfigLoaderService
      ],
      multi: true,
      useFactory: PreloadFactory
    }
  ],

Although I am not encountering any errors, the

this.router.url

is always "/" even when I access

localhost:4200/demo

leading to it entering the second condition. Can anyone pinpoint what could be going wrong?

Answer №1

One reason for this issue is that the router may still be initializing while you are trying to access it, causing it not to navigate internally to your desired URL.

To verify this, you can check the value of this.router.navigated in your config service. Initially, it will be false and only become true after a navigation event has been completed. For more information, refer to the documentation.

Possible Solution:

Instead of relying on the router, consider using window.location.pathname as a workaround.

initialize() {
    this.url = window.location.pathname; // use window.location.pathname instead of this.router.url
    console.log('Has router navigated?', this.router.navigated); // should show false initially
    console.log('Current URL:', this.url); // displays the correct URL
}

For a visual demonstration, check out this StackBlitz demo.

Answer №2

Is it possible to include the configuration in the route data?

{
                path: 'path',
                component: Component,
                data: myConfigForThisRoute,
            },

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

Angular compodoc tool is not considering *.d.ts files

Is there a way to make compodoc include .d.ts files in the documentation generation process for my Angular project? Even though I've added all .d.ts files to tsconfig.compodoc.json as shown below: { "include": [ "src/**/*.d. ...

Can the change listener be used to retrieve the selected option's number in a form-control?

This particular cell renderer is custom-made: drop-down-cell-renderer.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-drop-down-cell-renderer', templateUrl: './drop-down-cell-r ...

Step-by-step instructions for deactivating a specific FormControl within a FormArray

I've created a form that includes custom details: this.myform= new FormGroup({ ... customDetails: new FormArray([]), }); get customDetailsFormArray() { return this.shippingLocationDetailsUpdateForm.get( 'customDetails' ) as Form ...

How can I redirect a remote image URL to a local folder during development?

Currently, I am pulling image URLs from a database that was dumped from the production server. An example of one of these URLs is https://example.com/imageStorage/photo.jpg. These URLs are then used to display images in HTML templates using the following f ...

Testing Slack's Web API with Jest for mock purposes

Currently, I am working with two files. One file is where I set up a slack web API client to post a message and test it with a mocked value: main.ts: import { WebClient } from '@slack/web-api'; const slack = new WebClient(process.env.SLACK_API_K ...

What is the process for transitioning global reusable types to package types within turborepo?

When creating an app within the apps folder, a global.d.ts file is required with specific types defined like this: interface Window{ analytics: any; } This file should be designed to be reusable and placed in the packages/types directory for easy acce ...

After a recent deployment, the Angular PWA hosted on a NestJS server experiences unexpected crashes

I have set up an Angular PWA (version 11) on a NestJS (version 7) server. However, after each new deployment, the PWA crashes because the browser attempts to fetch a JavaScript file that no longer exists and then redirects to the root site (html): main.945 ...

How can one store the value of a promise or observable in an external variable?

I have thoroughly researched the .then() method and comprehend its functionality. In my current project, it is successfully providing me with the desired value. async getDay() { try { let ref = this.db.getDay(this.dateFirebase); ref.then(o ...

ways to display selected custom information with a choiceLabel in a dropdown using primeng

Is there a way to display custom data on a dropdown in Primeng while also showing the selected data as shown in the dropdown list? Please refer to both images below for clarification. <div class="p-grid" *ngIf="deleteUser" style=&quo ...

transitioning from angular cli version 1.7 to version 12

Looking for a detailed guide on upgrading from version 1.7 to the latest Angular version (12/11)? I currently have an app running on version 1.7 and couldn't find a step-by-step process here: upgrading angular Would it be safe to assume that the upgr ...

What could be causing the malfunction of the Bootstrap5 modal hide feature?

Today, I am facing an issue with hiding the Bootstrap5 modal in a TypeScript function. Despite trying to invoke the hide function on the modal element, it does not work as expected. Here is the minimal code snippet to reproduce this problem: import React f ...

Why is it that I have intellisense enabled for .js files but not for .ts files?

Below is the content of my package.json: { "name": "edge-node-api", "version": "1.0.0", "description": "Web API for Edge Electrons customers", "main": "api.js", "scripts": { "test": "echo \"Error: no test specified\" &am ...

Issues with the rating plugin functionality in Ionic 3

After following the instructions in this tutorial: http://ionicframework.com/docs/native/app-rate/ Even though I implemented the second method, I encountered the following error: Uncaught (in promise): TypeError: Cannot read property 'split' ...

How can I ensure that a user variable stored in an Angular6 service remains defined and accessible from other components?

Currently, I am working on an Angular app and facing a challenge. After receiving a user variable from an asynchronous call to Firestore Cloud, I noticed that the variable is successfully set (verified using console.log()). However, when I navigate between ...

Encountering an uncaughtException: Error stating that the module '....nextserverapphomelibworker.js' cannot be located while attempting to utilize pino.transport in Next.js

I recently set up a Next.js project with typescript using create-next-app. Opting for Pino as the logging library, recommended by Next.js, seemed like the logical choice. Initially, when I utilized Pino without incorporating its transport functionality, e ...

Tips for modifying the text color of a div that is being iterated through using ngFor

I am facing an issue with a div that is being looped using ngFor. What I want to achieve is when a user clicks on one of the divs in the loop, only that particular div should change its text color. If another div is clicked, it should change color while th ...

Unable to access the values of the object within the form

I am encountering an issue where I cannot retrieve object values in the form for editing/updating. The specific error message is as follows: ERROR TypeError: Cannot read properties of undefined (reading 'productName') at UpdateProductComponen ...

Setting up ESLint and Prettier with TypeScript on Node 20: A Guide

I attempted to set up Prettier with ESLint and crafted a configuration in settings.json to rectify errors upon saving, but the errors only manifest in .js files and not .ts files. How can I adjust this? Dependencies: "@eslint/js": "^9.4.0& ...

How can we utilize caching for an HTTP GET request in Angular 9 only when the navigator is offline?

My Angular 9 application utilizes http.get calls to communicate with an API, and I have integrated angular-pwa for offline capabilities. One challenge I am facing is ensuring that when the browser is online, two specific requests do not use cached respons ...

I am looking to transfer 'beforeEach' and 'afterEach' from the spec file to the global configuration file in WDIO [mocha, hook, wdio]

My E2E testing setup involves using the WebdriverIO library along with the mocha framework. During test execution, I want Mocha to automatically skip all subsequent checks in a test after encountering the first error, and proceed to the next test file. T ...