Trouble retrieving query parameters from a URL while trying to access URL parameters from a module

I am currently learning angular and facing a small problem that I'm unsure how to solve. My module looks like this:

const hostHandler = setContext((operation: any, context: any) => ({
  headers: {
    ...context?.headers,
    'X-Location-Hostname': hostname,
    'X-Location-Origin': origin,
    'X-App-Mode': test,
    'X-Language': get query param here,
  },
}));

The issue arises when I want to retrieve the URL parameter when someone enters "?country="UK"". In all the examples I've seen, they use something similar to this:

export class MyComponent {
  constructor(
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    const firstParam: string = this.route.snapshot.queryParamMap.get('country');

  }
}

Whenever I try to add this to my module, I encounter an error stating that I need a decorator. Is there a way for me to fetch the query parameter and send it along with the headers?

I attempted to obtain the query parameter in the app component and store it like so:

public ngOnInit() {
   this.store.dispatch(new GetNavigation());
   this.route.queryParams.subscribe(params => {
    if(params["country"])
    {
      localStorage.setItem('countryParam', params["country"]);
    }

  })
}

While this method works, the issue is that part of the code in the module executes before this, resulting in the correct value being retrieved from storage only upon page refresh when the storage is populated with the country parameter. Any advice on how to tackle this dilemma would be greatly appreciated.

Answer №1

Give this a shot

ngOnInit() {
  this.route.queryParams.pipe(
    map(params => params["country"])
  ).subscribe({
    next: (country) => { 
      localStorage.setItem('countryParam', country);
      const hostHandler = setContext((operation: any, context: any) => ({
        headers: {
          ...context?.headers,
          'X-Location-Hostname': hostname,
          'X-Location-Origin': origin,
          'X-App-Mode': test,
          'X-Language': get query param here,
        },
      });
      this.store.dispatch(new GetNavigation());
    }
  })
}

Make sure to nest the function calling setContext within the callback for the subscribe function.

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

Ensuring the Presence of a Legitimate Instance in NestJS

I have been working on validating my request with the Product entity DTO. Everything seems to be in order, except for the 'From' and 'To' fields. The validation works correctly for the Customer and Type fields, but when incorrect data i ...

Encountering an ECONNREFUSED error upon upgrading from Next.js 12 to 13

After upgrading from Nextjs 12 to 13, I am experiencing issues where every time I try to run the application, I encounter ECONNREFUSED to my local host but the port seems to keep changing. This results in the application not rendering properly. > <a ...

Is there a way to dynamically retrieve a JSON element in Typescript?

I am using a data grid throughout my application, and currently, I am retrieving the selected rowid with the following code. Here is the HTML snippet: <tbody> <tr *ngFor="let ddata of tableData.data; let i = index" (click)="setClickedRow(ddat ...

Struggling with defining content and background scripts while using AngularJS2 CLI to build a Chrome extension

After creating a brand new AngularJS-2 application using the cli tool from github, I discovered that running ng build compiles my sources into a /dist folder. As I am developing a chrome extension, I need to specify the location of my content script (whi ...

Is the neglected property being discarded?

First things first, let's talk about my class: class FavoriteFooBar { ... isPreferred: boolean = false; constructor() { this.isPreferred = false; } } Using a utility library called Uniquer, I arrange a list of FavoriteFooBar instances to pr ...

The system encountered difficulty handling a recursive structure

I am facing a challenge with a recursive JSON structure that needs to be stored as a series of maps with keys. The structure comprises flows and subflows that have references to each other. Here are the type declarations, noting that the issue lies in the ...

Issues with tsconfig Path Aliases in Angular 8+ when used in .spec files

While working on Angular testing, I encountered an issue where my spec files were not recognizing paths and displaying a red squiggle import warning in VS Code (and appearing under Problems), even though they functioned properly otherwise (testing worked, ...

Tips for customizing standard data types in TypeScript

Currently facing a challenge where I need to update a global type. Specifically, I am looking to modify the signature of the Element.prototype.animate function to make it optional. This is the approach I attempted: declare global { interface Element { ...

Verify Angular Reactive Form by clicking the button

Currently, I have a form set up using the FormBuilder to create it. However, my main concern is ensuring that validation only occurs upon clicking the button. Here is an excerpt of the HTML code: <input id="user-name" name="userName" ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...

Ways to stop dialog from disappearing in Reactjs

This code snippet demonstrates the implementation of a popup with buttons, where clicking the cancel button triggers a confirmation dialog. To make the popup disappear when clicked outside of it, the following event handling is employed: const popupRef = ...

Find the dominant color within the project's style sheets

Is there a method to extract the main color from an angular material theme and apply it in the css files of an angular project? Within a project, we can specify the primary color in a *.scss document as shown below: @import '~@angular/material/themi ...

When using ngStyle to bind a variable, the binding variable will be null

Currently, I am attempting to utilize ngStyle to set the background image. <div class="artist-banner fluid-banner-wrapper" [ngStyle]="{'background-image': 'url(../imgs/banner/' + event?.category + '.jpg)' }"> The fun ...

Using `publishReplay()` and `refCount()` in Angular does not behave as anticipated when dealing with subscriptions across multiple components

I am currently investigating the functionality of publishReplay in rxjs. I have encountered an example where it behaves as expected: const source = new Subject() const sourceWrapper = source.pipe( publishReplay(1), refCount() ) const subscribeTest1 = ...

Guide on moving elements to a different list with the help of the Angular DragDrop CDK Service

I encountered a unique situation while working on my project where I needed to implement a drag and drop feature for multiple lists using Angular CDK's DragDrop service. While I was able to successfully move items within a single list, transferring an ...

Incorporating a sidemenu into a DOM using Ionic2 and Angular2 Typescript

I am currently struggling to properly integrate the sidemenu from the app.ts file. app.html: <ion-menu [content]="content"></ion-menu> <ion-nav id="nav" [root]="rootPage" #content ></ion-nav> app.ts import {App, IonicApp,Page, ...

Error encountered in Azure Pipelines build task: Failure due to requirement for initialization

When I directly invoke index.js using node, everything works fine. However, when running the Mocha tests, the task fails with a "Must initialize" error message. This is how my tasks index.ts code looks like: import * as path from "path"; import tl = requ ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

Is there a way to deactivate multiple time periods in the MUI Time Picker?

Recently, I have been working on implementing a Time Picker feature with two boxes: [startTime] and [endTime]. The objective is to allow the time picker to select only available times based on predefined data: let times = [ { startTime: "01:00", en ...

Steps for adjusting the length in the getRangeLabel function of mat paginator

@Injectable() export class MyCustomPaginatorIntl extends MatPaginatorIntl { public getRangeLabel = (page: number, pageSize: number, length: number): string => { if (length === 0 || pageSize === 0) { return `${ ...