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

"Discover the versatility of implementing a single ag grid across various components, all while dynamically adjusting its style

I am facing an issue where I have an angular grid ag-grid in component1, which is being used in some other component2. Now, I need to use the same component1 in component3 but with a different class for ag-grid, specifically 'ag-grid-theme-dark'. ...

What is the correct way to assign multiple types to a single entity in TypeScript?

(code at the end) While attempting to write section.full.link, I encountered the following error: Property 'link' does not exist on type 'SectionSingle | SectionTitle | SectionHeaderMedia'. Property 'link' does not exist on ...

Angular Igx-calendar User Interface Component

I need assistance with implementing a form that includes a calendar for users to select specific dates. Below is the code snippet: Here is the HTML component file (about.component.html): <form [formGroup]="angForm" class="form-element"> <d ...

Defining Multiple Types in Typescript

I have created an interface in a TypeScript definition file named d.ts: declare module myModule { interface IQedModel { field: string | string[]; operator: string; } } In an Angular controller, I have utilized this interface like ...

Angular 4 - dealing with request timeouts

I am having trouble implementing a request every second in my code as the timeout function is not working correctly. matchlist.service.ts import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/timeout'; getMatch(matchId: num ...

Utilizing Express-WS app and TypeScript to manage sessions

I am currently working on setting up a node server using Typescript with the help of express and express-ws. My goal is to include Sessions in my application, so I have implemented express-session. Below you can find some pseudo code: import * as session ...

The JSONP request failed with an error stating: ReferenceError: document is not defined

My internship project involves developing a mobile application based on the website www.claroline.net using Nativescript and Angular 2. I have successfully implemented the login function, allowing users to sign in to the app. Next, I need to integrate not ...

What causes Angular2 to detect both reference changes and primitive changes even when the OnPush flag is enabled?

Take a look at this code snippet import {Component, OnInit, Input, OnChanges, DoCheck, ChangeDetectionStrategy} from 'angular2/core' @Component({ selector: 'child1', template: ` <div>reference change for entire object: { ...

Steps to reset Pipe in Angular 4

Is there a way to reinitialize a Pipe in Angular 4? I currently have a component that utilizes a Pipe. The component renders once with some data that uses the Pipe. If the data changes, the Pipe will also need to change. What is the best method to rein ...

How can I adjust the size and width of the autofocus cursor inside an input box using Angular?

How can I modify the height and width of the cursor in an input field with auto focus? app.component.html <input class="subdisplay" [ngModel]="input | number" type="text" (keyup)="getValue(box.value)" name ...

Checking React props in WebStorm using type definitions

Currently, I am utilizing WebStorm 2018.3.4 and attempting to discover how to conduct type checking on the props of a React component. Specifically, when a prop is designated as a string but is given a number, I would like WebStorm to display an error. To ...

What is the process for linking my component to my socket.io server?

I am facing a challenge in setting up a socket.io server to facilitate communication between two components: a command interface for sending data, and an overlay component for receiving it. Below is the code snippet: interface.component.html : <input ...

Understanding 'this' in ChartJS within an Angular application

Here is my event handler for chartJS in Angular that I created: legend: { onClick: this.toggleLegendClickHandler After changing the text of the y scale title, I need to update the chart. I am looking to accomplish this by calling this._chart.cha ...

What are the benefits of dealing with various versions of Angular?

Currently, I am using Angular version 8.2.14 which was installed globally by running the command npm install -g @angular/cli. All my projects are also built on this same version of Angular. With the recent release of Angular version 9, I am contemplating ...

Can someone guide me on capturing an API response error using observables?

Currently working with Angular 4, my API call is functioning properly, returning the expected JSON for successful responses. However, in case of an error response, instead of receiving a JSON response as expected, I end up with a 404 HTML page (which is no ...

"Observables in RxJs: Climbing the Stairs of

Previously, I utilized Promise with async/await syntax in my Typescript code like this: const fooData = await AsyncFooData(); const barData = await AsyncBarData(); ... perform actions using fooData and barData However, when using RxJs Observable<T> ...

Utilizing Glassfish Application Server and MSSQL Database for Angular Front-End Authentication in Jakarta

Embarking on my journey in the realm of web development, I am eager to implement authentication for my full-stack application. Armed with Angular 13 on the front end, Jakarta 9 running on Glassfish app server, and MSSQL database, I find myself at a loss on ...

Error message in Angular 6: Unable to bind to 'org' as it is not recognized as a valid property of 'appCycleDirection' (Directive)

Here is the code snippet of a directive I have created: import { Directive, Input, OnInit } from '@angular/core'; import {GoogleMapsAPIWrapper} from '@agm/core'; declare let google: any; @Directive({ // tslint:disable-next-line:dire ...

Can you explain the distinction between interfaces containing function properties written as "f()" and "f: () =>"?

Let's take a look at two interfaces, A and B: interface A {f(): number} interface B {f: () => number} I have experimented with the following: var a: A = {f: function() {return 1}} var a: A = {f: () => 1} var b: B = {f: function() {return 1}} ...

Dealing with server-side errors while utilizing react-query and formik

This login page utilizes formik and I am encountering some issues: const handleLogin = () => { const login = useLoginMutation(); return ( <div> <Formik initialValues={{ email: "", password: "" }} ...