One way to include query parameters before initiating navigation in Angular

Imagine having two components called A and B. When Component A navigates to /a?random=random and B navigates to /b, I need to include the authUser query parameter before the navigation begins. This way, the final URLs should look like this: /a?random=random&authUser=1 and /b?authUser=1 respectively. However, the issue arises when the URL for component A ends up looking like /a?authUser=1 after adding the authUser queryParam, instead of /a?random=random&authUser=1.

You can check out the code in this StackBlitz link.

// App component
 ngOnInit() {
    this.router.events.subscribe((event) => {
      if(event instanceof NavigationStart) {
         if (!event.url.includes('authUser')) {
          // remove queryParams
          const url = event.url.split('?')[0];
          if (url !== '/') {
            // /a/etc => ['a','etc']
            const newUrl = url.split('/').filter(_subUrl => _subUrl);
            this.router.navigate(newUrl, { queryParams: { authUser: '1' }, queryParamsHandling: 'merge' });
          }
        }
      }
    })
  }

  navigateToA() {
    this.router.navigate(['a'], { queryParams: { random: 'random' } });
  }

  navigateToB() {
    this.router.navigate(['b']);
  }

I prefer not to modify the navigate methods of component A and B because changing them in a real application would require making modifications to every navigate method, which is not considered good practice.

Answer №1

example for query parameter handling using Angular Router - this.router.navigate([/${this.appStatus.baseUrl}/predict/result

], {queryParams: {vsgid: vsgid, sid: sid, logo: logo}});

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

Oops, it seems like there was an issue with NextJS 13 Error. The createContext functionality can only be used in Client Components. To resolve this, simply add the "use client" directive at the

**Issue: The error states that createContext only works in Client Components and suggests adding the "use client" directive at the top of the file to resolve it. Can you explain why this error is occurring? // layout.tsx import Layout from "./componen ...

The error message states: "An uncaught TypeError has occurred - the object does not possess the 'jqzoom' method."

I am encountering a browser console error while working on a project involving a magento website. Specifically, I need to implement the jqzoom feature on the product view page. Here's what I have done so far: Added jQuery Included the jqzoom librar ...

Which rxjs operator functions similarly to concatmap, but delays the firing of the next request until the current one is completed?

Imagine if I need to make multiple api calls with a high risk of encountering race conditions. If I send 3 requests simultaneously to update the same data on the server, some of the information could be lost. In order to prevent this data loss, I want to ...

Sorting an array of objects using an array of corresponding IDs

Given an array activeIds which contains the ids of active services and another array servicesList which holds objects of various services. For example, let's consider: activeIds = [202, 204] serviceList = [{ "id":201, ...

Creating a Tailored Validation Function in Angular 6

Looking to develop a custom generic validator that accepts the regular expression pattern and the property name (from a formgroup) as parameters? Take a look at this code snippet: UserName: new FormControl('', [ Validators.require ...

Display a div when a specific moment in the video is reached and then conceal it at a different

I'm attempting to display a div at a specific time during a video and have it disappear 2 seconds later. However, the current code I've tried is not producing the desired result: $(document).ready(function() { $("#element_1").hide(); document ...

A guide to sending props to a CSS class in Vue 3

I need to develop a custom toast component that includes a personalized message and class. While I have successfully passed the message as props, I am encountering difficulties in applying the bootstrap class. Component File: Toast.vue <script ...

At what point is it necessary to generate a new vertex array object when sketching numerous objects?

I'm embarking on a game development project using WebGL. Currently, I have three textures in my arsenal- one for letters used in the font, another for character sprites, and a tilemap texture for the world. With these large textures at hand, I find m ...

Searching for the right approach to implementing useState with count in order to efficiently add new items in Next.js

Although my code currently functions, I have a feeling that I am not utilizing the useState and useEffect hooks in the best way to achieve my ultimate goal. Let me explain further - I have a button with an onClick event in a separate component, which passe ...

What steps should be taken to restart an AJAX call that has failed previously?

My issue involves an ajax call that must run and if it fails, it should be reinitialized. While I have looked into some posts mentioning a failure function where we can inform the user about the failed ajax call and execute a set of functions. However, I ...

Angularjs Dependency Module Aggregation

Just diving into angularjs, I have a question. Can I include multiple dependency modules in AngularJS? sample code: angular.module('myApp', ['dependency1','dependency2']); I attempted this approach as well without success ...

Where should you position the $watch function in Angular?

Suppose I have a promise object that my page uses to retrieve data, like so: promise.then(function (data) { $scope.myData = data; }); In addition to this, I have watches on objects located elsewhere on the page. When it comes to watching data provide ...

What is the method for moving one div above or below another div using the scroll bar?

Here's the scenario I'm facing: I have rows with buttons that, when clicked, reveal a set of options. The challenge is that depending on where the row is located on the page, the settings need to open either above or below the button. When the b ...

Exchange a TypeScript data type with a different one within an object

I am currently working with the following type definitions: type Target = number | undefined; type MyObject = { some: string; properties: string; id: Target; } I am trying to find a generic solution to replace instances of Target with number ...

Delete any   tags from HTML tables

I have created a print layout using HTML and when retrieving data from a database, I am noticing that the string contains the tags &nbsp; as seen in the image below: https://i.sstatic.net/rR3lc.png When I use print_r() in the console, the result is s ...

Struggling to modify a JSON value within a loop

I am currently developing a JavaScript code that involves updating one JSON based on conditions from another JSON. Below is the code I have written. const a = [{ "a": "Not Started" }, { "b": "Not Started" }, { "c": "Not Started" }, { "d": "Not S ...

Which packages will be included once ng eject is executed?

After executing the ng eject command, I observed the following messages displayed in the console. The last line indicates that packages have been added as a result of running the command. What specific packages are included when we run ng eject? For refe ...

Stop processing the current websocket connection once a new websocket request is received

Currently, I am utilizing the npm ws module (or its wrapper named isomorphic-ws) for establishing a websocket connection. NPM Module: isomorphic-ws This setup allows me to retrieve an array of data from a websocket++ server situated on the same local mac ...

What is the best way to organize the data retrieved from the api into a map?

In my search page component, I display the search results based on the user's query input. Here is the code snippet: "use client"; import { useSearchParams } from "next/navigation"; import useFetch from "../hooks/useFetch&qu ...

What is the best way to nest a table within another table in AngularJS, especially when dealing with tables of varying numbers of rows and columns

I am currently working on creating a dynamic table that maps various enemy courses of action in the columns to friendly courses of action in the rows. Each cell in the table will contain a 2x2 matrix displaying the number of friendly casualties, ammo loss, ...