After a screen refresh in Angular 5, ActivatedRoute.queryParams becomes null

Help needed!

I'm facing a dilemma with the url below

https://xxx.io/#/route1/yyyyyyyy?tj=3&bd=7

After navigating to it, I utilize this code:

this.route.queryParams.subscribe((res: any) => {
        console.log('tj: ' + res.tj)
        console.log('bd: ' + res.bd)

The expected output is tj: 3 and bd: 7. However, upon refreshing the screen, res.tj and res.bd turn undefined. How could this happen?

Initially, I noticed that upon refresh, the url changes to:

https://xxx.io/#/route1/yyyyyyyy%3D3&bd%3D7

This alteration was due to encoding issues in the url structure, hence I implemented a CustomUrlSerializer:

import { UrlSerializer, UrlTree, DefaultUrlSerializer } from '@angular/router';

export class CustomUrlSerializer implements UrlSerializer {

  parse(url: string): UrlTree {
    const dus = new DefaultUrlSerializer();
    return dus.parse(url);
  }

  serialize(tree: UrlTree): any {
      const dus = new DefaultUrlSerializer();
      let path = dus.serialize(tree);
      return path.replace("%3F", "?").replace(/%3D/g, "=");
  }
}

With this modification, the url returns to its correct form after refreshing:

https://xxx.io/#/route1/yyyyyyyy?tj=3&bd=7

However, the issue of res.tj and ts.bd remaining undefined persists! Any insights on why this occurs and how to resolve it would be greatly appreciated.

Thank you!

Answer №1

The Angular NavigationExtras interface includes a useful property called preserveQueryParams. If set to true, it can be beneficial in your scenario

Here's an example of how you can use it:

this.router.navigate(['/details'], { preserveQueryParams: true });

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

Changing the names of properties within a intricate JSON structure

I have a JSON data structure that is quite complex, like the one shown below: const json = '{"desc":"zzz", "details": { "id": 1, "name": "abc", "categoryDetails": { "cid": ...

Pass multiple JSON objects to Angular and render them in an HTML template

Hey there! I'm looking for assistance with integrating a JSON object containing product data into an Angular HTML file. Although I've managed to make it work in the console (check out the image below), I'm unsure how to display this informat ...

Link checkboxes to a value rather than using true/false with reactive forms

Looking for help with reactive/model-driven forms to bind an array of checkboxes to a list of values, rather than boolean values. Here's the issue demonstrated in this Plunker: http://plnkr.co/edit/a9OdMAq2YIwQFo7gixbj?p=preview. Currently, the value ...

Converting an object within an object into an Angular Class (Type)

Is there a way to convert the value of obj.category into the Category type as shown in the example below? I specifically need this conversion in order to select options in a dropdown. export class Category{ id: number; name: string; construc ...

Is there a way to limit the typing of `T extends {}` so that `keyof T` is always a string?

My current mapping type has been effective in many scenarios: type WithKeyPrefix<P extends string, T extends {}> = { [K in Extract<keyof T, string> as `${P}/${K}`]: T[K]; }; However, I'm facing an issue with rejecting objects that have ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

Is there a way to link my ionic application to dual API URLs within a single webpage? Additionally, how can I transfer the ID from the information received from the first URL to the second URL efficiently?

I am currently in the process of developing an Ionic recipe application. The home page is designed to display a list of recipes names, ids, and images by fetching data from an API endpoint at www.forexample/recipeslist.com. My goal is to create functiona ...

Relentless Recursion in Angular's Parent Component

Take a look at the Stackblitz to replicate the issue Hey there! I have an Angular7 application with a parent component named timesheet, and a child component called row. What I'm trying to achieve is having the parent component, timesheet, dynamicall ...

What is the best way to ensure an observable has finished before retrieving a value?

Looking at the function provided below: public getAssemblyTree(id: number) { .... const request = from(fetch(targetUrl.toString(), { headers: { 'responseType': 'json' }, method: 'GET' })); request.sub ...

Searching through the entirety of a meteor for text can yield valuable information. Once a client subscribes to the search

Trying to implement a full text search feature in Meteor with Angular 2. Here is my publish function: Meteor.publish("search", (searchValue) => { console.log(searchValue); if (searchValue) { return Nutrition.find( {$text: ...

An unexpected 'foo' key was discovered in the current state being processed by the reducer when using redux-toolkit's configure store and a customized store enhancer

I've been working on developing a custom store enhancer to add new values to my root state. However, I've encountered an unexpected key error after delving into the complexities of custom enhancers. While I can see the new state part in devtools ...

Importing and declaring child components in Angular testing with Karma, Jasmine, and TestBed is essential for comprehensive component testing. This ensures all

Challenge Description: When writing unit tests using karma/jasmine for an angular component that utilizes other angular components, there is a need to recursively import all components included in child components into the testbed configuration. Is there a ...

Angularfire/Firebase utilizes the Authorization Code Grant flow for OAuth

I am trying to understand the authentication flow used by applications that depend on Firebase for single sign-on authentication. While I know that most SPA and client applications use the "implicit flow" due to everything happening in the browser without ...

The animations in Angular 6 material are failing to function

The animations in material components seem to be causing some issues. I've tried implementing the sidenav and menu components, but the smooth animation effect is not working as expected. I suspect that the problem lies with BrowserAnimationsModule. De ...

Attempting to retrieve a file from the database with the utilization of Angular 5 and ASP.NET Core

I've been struggling with downloading a file from the database using its unique identifier. Can anyone provide guidance on what steps are necessary to achieve this successfully? The FileUpload table contains the following columns pertaining to the fi ...

When utilized in a nested component, the service is found to be null

When developing a nested component, I encounter an issue where the injected service is null. How can I successfully use a service in a nested component? export class ActivityComponent implements OnInit { constructor( . . public accountServ ...

Error in Cypress API response: The property 'body' is not found in the type 'Interception'.ts(2339)

When triggering an API request through a Cypress event, I need to extract the value of the applicationId parameter from the response body. This value is crucial for setting a variable or alias that will be used later in the code, specifically to provide it ...

Reducing file size when uploading images in Angular4 through image compression

saveImage(event: any, type, image_type) { this.uploadImageFlag = true; const fileList: FileList = event.target.files; if (fileList.length > 0) { const file: File = fileList[0] this.files.set('files', file, file.name) ...

TypeScript encountered an error: The get call is missing 0 type arguments

I encountered a typescript error stating "Expected 0 type arguments, but got 1" in the line where my get call is returning. Can you help me identify what is wrong with my get call in this code snippet? public get(params: SummaryParams): Observable&l ...

Why isn't my event handler triggering when working with TypeScript services and observables?

I am currently working on a project in Angular 2 where I am incorporating observables and services in typescript. However, I have encountered an issue where the event handler in my observable is not being triggered. Below is the code snippet: The Service ...