Data in Angular is not getting transmitted properly through the routing system

I have a situation where I am sending data through routing and fetching it. Here's the code snippet for sending the data:

    navigateWithState(x) {
        console.log(x);
        this.router.navigateByUrl('/full-layout/add-form/1', { queryParams: {x} });
    }

And here is the code snippet for fetching the data:

 constructor(private route: ActivatedRoute) {

      if(this.options == 1){
      console.log('edit');
      this.route
      .queryParams
      .subscribe(params => {
        console.log(params);
      });
    }
    else{
      console.log('add');

    }
}

Despite having the data in the console, when passing data through the router, it's showing up as an empty array. Here's the console screenshot: https://i.sstatic.net/EOeBa.png

I tried using navigationExtras like this:

navigateWithState(x) {
    console.log(x);
    const queryParams: any = {};

    queryParams.myArray = JSON.stringify(x);

    const navigationExtras: NavigationExtras = {
      queryParams
    };
    this.router.navigateByUrl('/full-layout/add-form/1', navigationExtras);

Then, in the .ts file, I tried fetching the data like this:

if(this.options == 1){
  console.log('edit');
  const myArray = this.route.snapshot.queryParamMap.get('myArray');
  console.log(myArray);

}
else{
  console.log('add');

}

But it's showing null in myArray instead of the actual data.

Answer №1

When utilizing the navigateByUrl method, you must include the parameters in the URL. On the other hand, if you are using navigate, you can pass the parameters directly.

  navigateWithState(x) {
        console.log(x);
        this.router.navigateByUrl(`/full-layout/add-form/1?x=${JSON.stringify(x)}`);
    }

When using the navigate method, you can retrieve the values from the parameters.

  navigateWithState(x) {
        console.log(x);
        this.router.navigate(['/full-layout/add-form/1'], { queryParams: {x: JSON.stringify(x)}}); // Remember to parse it to JSON when retrieving the values, like JSON.parse('values');
}

Answer №2

When utilizing navigateByUrl in Angular, make sure to include any required parameters as shown in the example below:

this.router.navigateByUrl(`/full-layout/add-form/1?x=${x}`);

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

What are the steps to prevent exceptions from being displayed when an Angular project times out?

Despite the absence of a debugger or breakpoints provided, the execution halts here whenever the Angular project is logged out due to timeout. https://i.sstatic.net/OFsvI.png ...

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

Enhancing a UMD module definition with TypeScript 2: A step-by-step guide

Currently, I am in the process of creating TypeScript definition files for two libraries that are meant to be used with the new @types approach. Both libraries adhere to the UMD pattern, allowing them to be consumed either as modules or by referencing them ...

What could be causing the interceptor to consistently return "null" as the value when using BehaviorSubject, instead of returning the updated value?

In the process of creating an authentication application utilizing the PEAN stack (PostgreSQL - ExpressJS - Angular - NodeJS). To verify the user's sign-in status, the following steps are taken: On the backend, the session cookie is checked to deter ...

My HTML components are not showing alert messages at the top as expected

My application's alert message is supposed to stay on top of all other HTML elements as the page scrolls. However, it seems to be going behind certain components instead of staying on top like it should. This issue is puzzling because all components u ...

CSS specificity in Angular components utilizing the /deep/ selector to target a class outside of the component's scope

I have developed a button component for an Angular Component Library that I am currently working on. The button functions correctly, and its implementation is as follows: <sio-button [buttonLabel]="'Button Text'" [buttonFormat]="&apos ...

Unexpected token { in Fuse-Box when using Typescript

Here's the beginning of my fuse.ts file import { CSSPluginOptions } from 'fuse-box/plugins/stylesheet/CSSplugin'; import { argv } from 'yargs'; import * as path from 'path'; import { CSSPlugin, CSSResourcePlugin, Env ...

Is there a way to revert my Ionic CLI back to the previous version that I had installed?

Having just updated to version 3.2.0, I am encountering numerous issues, such as the malfunctioning of the ionic serve command. ...

Exploring Angular's filtering capabilities and the ngModelChange binding

Currently, I am in the process of working on a project for a hotel. Specifically, I have been focusing on developing a reservation screen where users can input information such as the hotel name, region name, check-in and check-out dates, along with the nu ...

An instance of an object is being added instead of parameters

I'm having some trouble making a server call using promises. Whenever I try to add my parameters, they end up showing as 'object%20Object' Here's the code snippet for the call: import { Injectable } from '@angular/core'; imp ...

Merely using Array.isArray check is insufficient to prompt the TypeScript compiler about a potential array value

I have a method where the type can be an array, but I need to verify that it is not an array before accessing the argument. However, despite my check, I am still encountering the following error (excerpt) on line this.setState({ cuisine });: The type &ap ...

Angular 7 ng-select validation with required form control

Currently, I am utilizing the ng-select plugin for a dropdown search feature, but I am encountering issues with validation when a selection is not made from the dropdown menu. Here is how I have implemented it: <div class="form-group"> <ng-sel ...

The responsive table fails to completely fill the column it is contained within

In my Angular application, I am integrating Bootstrap 4. Within one of the component's HTML files, I am attempting to embed a responsive table within a grid row. I have followed the instructions by nesting the "table" div inside another div with the ...

Encountering [Object Object] within an angular2 app

https://i.stack.imgur.com/iceKH.pngI recently created an angular2 application using ngrx/effects for handling http calls. My reference point was an application on GitHub. However, I am facing an issue where the response from the HTTP call is not displaying ...

Running Ng serve is not functioning properly with no indications of errors or messages to identify the issue

Recently, after updating to MacOS Sonoma, I encountered an issue where the ng serve command stopped working. While ng version is still functional and displays the current version, running ng serve in my project doesn't yield any results. The terminal ...

I am experiencing issues with arrow pagination not functioning properly in TypeScript

My current project involves building a customer table with 10 customers displayed on each page. Additionally, there are arrows below the table to help users navigate and view more customers. Unfortunately, there seems to be an issue with the functionality ...

Include [op.and] in the Sequelize query object

I want to construct my Sequelize query object based on input parameters. It functions well for database keys, as shown in the example below: let query = { where: { id: 5 } } if (inputName) { query['where']['name'] = { nam ...

The conundrum of nested function wrapping in Typescript and its impact on

Upon calling the following function, it returns a Promise<boolean>: const fnc = (i:number) : Promise<boolean> => Promise.resolve(true) // Promise<boolean> const res1 = errorHandler(errorPredicates.sdkError1, fnc, null, 4); However, ...

What are the reasons behind the inability to implement an Angular custom pipe in a component?

Lately, my focus has been on creating an e-commerce application using Angular 14. One of the key features I am working on is the ability to filter products by brand. To achieve this, I have developed a custom pipe called app/pipes/filter-products.pipe.ts: ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...