What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me...

My goal is to redirect to a URL like this:

this.router.navigateByUrl('/products');

I want to pass an array and retrieve it in the component with the active link products using skip location change without displaying anything in the URL.

The array will look like this:

products = [{"id":1,"name":"Product One"},{"id":2,"name":"Product Three"},{"id":3,"name":"Product Six"}]

I need to pass this entire array in the router link and retrieve it in another component (products) with skipLocationChange set to true...

I tried using sharedService, but I encountered issues with data loading at the right time, which led me to decide to use a router link instead...

If you believe this approach isn't ideal, please suggest an alternative method that doesn't involve shared service...

Answer №1

When dealing with large datasets in Angular, utilizing Angular Services is a recommended approach.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class ExampleService {

private subject = new Subject<any>();  

updateRouteData(data) {
    this.subject.next(data);
}

routeData(): Observable<any> {
    return this.subject.asObservable();
}
}

To use these services within your components:

For setting route data:

import { ExampleService } from '/example.service'

export class ComponentOne{

constructor(private exampleService:ExampleService){
   this.exampleService.updateRouteData(data)
}

You can retrieve the data like so:

import { ExampleService } from '/example.service'

export class ComponentTwo{

constructor(private exampleService:ExampleService){
   this.exampleService.routeData().subscribe(data => {
       console.log(data)
   })
}

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

Tips for extracting the chosen value from a dropdown list within a table cell using JavaScript

Here is an example of an HTML element: <td> <select> <option value="Polygon 47">Polygon 47</option> <option value="Polygon 49">Polygon 49</option> </select> </td> I am looking for a ...

When refreshing a page in Next.js, the loading indicator does not properly turn off

I'm currently working on my portfolio using next.js and I have implemented a 'loading' state to prevent displaying partially loaded gallery images. The 'loading' state should turn off (set to 0) once all the photos are fully loaded ...

Navbar Growth Effect

I'm attempting to create an expanding effect in my navbar using Angular. When I click on "show information," the content should slide up. The issue is that the top part of my footer does not follow the effect. I have tried something like: <foot ...

Is there a JavaScript alternative to wget for downloading files from a specified url?

"wget http://www.example.com/file.doc" can be used to download the file to the local disk. Is there an equivalent way to achieve this in JavaScript? For example, let's look at the following HTML snippet. <html> <head> <script langu ...

What is the best way to create a reusable component for a dialog box or modal window?

I have been working on developing a reusable dialog component with a yes or no button at the bottom. The main idea behind this is to create a user confirmation dialog that prompts the user to confirm their entered information before proceeding. import Re ...

What sets apart optionalDependencies from peerDependencies in the Meta optional?

Why are both marking dependency as optional and what is the specific use-case of each? Is peerDependenciesMeta intended for npm packages while optionalDependencies is meant for projects? For example, in my npm package, certain modules require dependency ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

Next.js fails to refresh the content upon initial view

Snippet from my index.js file: import Post from "@/components/Post" import Modal from "@/components/Modal" import {useState} from "react" export default function Home() { // Setting up states const [modalTitle, setModalTitle] = useState('Title&a ...

Invoking a plugin method in jQuery within a callback function

Utilizing a boilerplate plugin design, my code structure resembles this: ;(function ( $, window, document, undefined ) { var pluginName = "test", defaults = {}; function test( element, options ) { this.init(); } test.pro ...

What is the best way to extract values from a JavaScript function?

As someone who is new to Javascript, I am interested in learning how to retrieve values from a function. In the given code snippet, my goal is to extract TheName, TheHeight, TheGender, and TheSexuality when executing the function so that I can utilize the ...

The TypeScriptLab.ts file is generating an error message at line 23, character 28, where it is expecting a comma

I am attempting to convert a ts file to a js file. My goal is to enter some numbers into a textarea, and then calculate the average of those numbers. However, I encountered an error: TypeScriptLab.ts(23,28): error TS1005: ',' expected. I have in ...

Tips for transforming code with the use of the then block in javascript, react, and cypress

In my code snippet below, I have several nested 'then' clauses. This code is used to test my JavaScript and React code with Cypress. { export const waitForItems = (retries, nrItems) => { cy.apiGetItems().then(items => { if(items ...

The type 'IContact[]' given does not match the expected type 'FetchContactsSuccessPayload' for the parameter

I've been diving into my project involving react redux-saga with TypeScript and I'm facing an issue with a type error within my saga file. This is my first experience with TypeScript. The error originates from the saga.ts file, specifically this ...

Unable to populate an array with JSON elements within a for loop triggered by useEffect

In my code, there is an issue with the array candleRealTimeDataQueue not updating correctly. Below is the snippet of the problematic code: let candleCurrentJSONDataWS = null; var candleRealTimeDataQueue = []; let tempDateTime = null; let ca ...

Can you provide a basic illustration of how routes are implemented in AngularJS?

After searching through numerous examples of using Routes with Angular, I have unfortunately not been able to find a working solution. Even the example provided in the official guide did not work properly (clicking on it resulted in a wrong URL that did no ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

Upgrade from Next.js version 12

Greetings to all! I have recently been assigned the task of migrating a project from next.js version 12 to the latest version. The changes in page routing and app routing are posing some challenges for me as I attempt to migrate the entire website. Is ther ...

Cutting-edge framework for Single Page Applications

Can you assist me in identifying the most recent framework suitable for creating single page applications? Your help is greatly appreciated. Thank you. ...

Create a div element that expands to occupy the remaining space of the screen's height

I am trying to adjust the min-height of content2 to be equal to the screen height minus the height of other divs. In the current HTML/CSS setup provided below, the resulting outcome exceeds the screen height. How can I achieve my desired effect? The foote ...

jQuery for Revealing or Concealing Combinations of Divs

UPDATE: Check out this answer. I have a complex query related to jQuery/JavaScript. I came across a post dealing with a similar issue here, but my code structure is different as it does not involve raw HTML or anchor tags. Essentially, I am working on ...