Tips for adding or updating query parameters in Angular2

When navigating and updating settings in my app, I am utilizing query parameters that I need to retain and update. Adding a parameter is simple using the following method.

onNavigate() {
this.router.navigate(['reports'], {queryParams: {'report': this.chart}, preserveQueryParams:true});
}

However, the issue arises when I try to change the report parameter and append new parameters to the URL throughout the application.

By using preserveQueryParams: true, my parameters become read-only. I am looking for a way to update existing parameters and add new ones without losing any unless they are intentionally cleared.

Is there a way to achieve this without losing the current set parameters?

Answer №1

It seems that the function preserveQueryParams is not designed to automatically add or update the queryParams for your application.

You will need to create your own logic to retrieve the existing query parameters, make any necessary updates, and then pass them along when navigating.

   this.route.queryParams.subscribe(qparams => {
     this.currentQueryParams= qparams;
   });

    updatedqueryParams = // utilize this.currentQueryParams to make any necessary updates
    let navigationExtras: NavigationExtras = {
      queryParams: updatedqueryParams
    };

    // Navigate to the desired page with the updated extras
    this.router.navigate(['<some path>'], navigationExtras);

The purpose of preserveQueryParams is to retain the current global query parameters that you are navigating from.

For example, if the current URL is:

 dashboard?debug=true&somevar=1

And you use the following code:

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

The new route will then be:

admin?debug=true&somevar=1

I hope this explanation clarifies things for you!

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

Using string interpolation and fetching a random value from an enum: a comprehensive guide

My task is to create random offers with different attributes, one of which is the status of the offer as an enum. The status can be “NEW”, “FOR_SALE”, “SOLD”, “PAID”, “DELIVERED”, “CLOSED”, “EXPIRED”, or “WITHDRAWN”. I need ...

Error: 'next' is not defined in the beforeRouteUpdate method

@Component({ mixins: [template], components: { Sidebar } }) export default class AppContentLayout extends Vue { @Prop({default: 'AppContent'}) title: string; @Watch('$route') beforeRouteUpdateHandler (to: Object, fro ...

Angular navigation did not work as expected

Created a basic webpage using Angular CLI version 8.3. The issue is as follows: For example: www.domainname.com is working fine. www.domainname.com/basicprinciples will work if visited through the main page, but it does not work when directly visiting w ...

Troubleshooting: Why is Angular2 ngClass malfunctioning?

I am having trouble adding a class based on a condition <tr *ngFor="let time of times; let i = index"> <td [ngClass]="{'red-time':checkInvalid(time['Proles Arrive'])}">{{time['Proles Arrive']}}</td& ...

Strategies for Patience: Juggling Multiple Requests

Trying to determine the most efficient way to handle multiple requests simultaneously without waiting for each other. // table filling public SUB_getActSearch: Subscription; // table filling 2 public SUB_getDeclarationSearch: Subscription; public fillTa ...

Ensuring the correct setup of PixiJS within Angular 6

I am facing an issue with correctly installing PixiJS in my Angular 6 project. I attempted to: npm install pixi.js and then: npm install --save @types/pixi.js I also adjusted my path in the script array: "scripts": [ "node_modules/pixi.js/di ...

Utilizing "regression-js" within an Angular 2 project: A comprehensive guide

I have integrated the Regression npm module https://www.npmjs.com/package/regression into my Angular 2 application to utilize the Linear Regression functionality. I installed the package using "npm install regression". However, I encountered errors while a ...

Ways to update the value of an object in typescript

When working with an array of objects, I encountered an issue while trying to change the object value. The error message "Type 'string | boolean' is not assignable to type 'never'. Type 'string' is not assignable to type &apos ...

Angular2/Typescript: Transforming a Javascript/Typescript Date into a C# DateTime string on the client side

Currently immersed in an Angular2/Typescript project, I am faced with the task of sending a date to a C# backend. Despite my extensive research, all I could uncover through Google searches was information on converting the date on the backend side. My la ...

What's the trick to aligning the label on the material-ui text field to the right side?

I am working on a React project with an RTL layout using material-ui and typescript. I am struggling to align the label of a text field to the right. Can anyone help me with this? https://i.sstatic.net/UrkIF.jpg ...

Creating columns on the fly within a row

I would like to create a layout where images are displayed in one row, but if the screen size changes, I don't want them to wrap and display below. Instead, I want to show a button that redirects to another page. I'm not sure how to achieve this. ...

Utilize Typescript to expand the functionality of the Express Request object

Is there a way to add a custom property to the request object in Express middleware using TypeScript without resorting to bracket notation? I am struggling to find a solution that satisfies this requirement. I would ideally like to achieve something like ...

Error Message: "Module not found - Module TS2307 cannot be located

When I try to open a Typescript project in VSCode, I encounter the error message "ts2307 Cannot find module 'react' or its corresponding type declarations". However, everything works fine when I use WebStorm. The project was created using Create ...

Display and conceal table columns dynamically in Vue by utilizing the Vuetify data table functionality

Looking for an example: How to show hide columns of vuetify data table using v-select list I have created something similar, but I'm facing an issue where the table doesn't refresh when changing the header data: https://codepen.io/Meff1/pen/vY ...

Dealing with routing problems within sub-routes using Angular 2 and Express, attempting to serve content from sub-folders

I am currently using Express to serve a local Angular2 application. To enable the Angular2 app to access various node_modules from Express, I have set up the following configuration: config.dependencies = [ { staticPath: './node_modules/@angular/&a ...

What is the best method to add information into an array using Angular 7?

My data consists of an array of objects : [ { indicatorDatasource: "trackingError", un_an: 0, trois_ans: 0, cinq_ans: 0 }, { indicatorDatasource: "annualisedFundPerformance", un_an: 19.749642029434945, trois ...

Using a string array in a JSON model - a simple guide

Just starting out with Angular and having some difficulty integrating my JSON data effectively. Inside my service, I have temporary JSON data that is structured using a model to define the different types of information within it. My objective is to creat ...

Unable to activate ngx-scrollbar RTL mode in my Angular application

I have been working on implementing Right-to-Left (RTL) support for scrolling using the ngx-scrollbar package in my Angular project. Unfortunately, I am facing an issue where the scrollbar does not seem to function correctly when in RTL mode. To add ngx-s ...

Using Ionic2, include NavController into Injectable Service

Having an issue with an Injectable Service in Angular2 with Ionic2 framework. Here is how my service is structured: import {Injectable} from '@angular/core'; import {NavController} from 'ionic-angular'; @Injectable() export class Vie ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...