Navigate through the router using query parameters in Angular 5

Encountering an issue with routing to a route containing query params. Here is the function in question:

goToLink(link) {
    this.router.navigate([`${link.split('?')[0]}`, { queryParams: this.sortParams(link)}]);
}

Additionally, there is another function involved:

sortParams(link) {
    let queryParams = url.split('?')[1];
    let params = queryParams.split('&');
    let pair = null;
    let data = {};
    params.forEach((d) => {
      pair = d.split('=');
      data[`${pair[0]}`] = pair[1];
    });
    return data;
}

The goToLink() function processes URLs with query parameters, extracting and storing them into an object using the sortParams() function. When provided with a URL like this:

https://website.com/page?id=37&username=jimmy

An object is returned that looks like this:

{id: 37, username: 'jimmy'}

This object is then passed as the query parameter when using this.router.navigate(). However, upon routing, the query params appear as:

/page;queryParams=%5Bobject%20Object%5D

Is there something I am missing or doing incorrectly in my implementation?

Appreciate any assistance!

EDIT

Upon changing the function to:

this.router.navigate([`${link.split('?')[0]}`, { queryParams: {id: 37, username: 'jimmy'}}]);

The same URL result is observed:

/page;queryParams=%5Bobject%20Object%5D

Answer №1

It is possible that you mistakenly placed the closing bracket intended for the first parameter at the end of the route statement.

Your code:

// The closing bracket '}}]);' should only be included within the first parameter
this.router.navigate([`${link.split('?')[0]}`, { queryParams: {id: 37, username: 'jimmy'}}]);

Update route:

Please ensure to place the ] close bracket within the first parameter and not at the end of the route statement.

// Updated line: '}});'
this.router.navigate([`${link.split('?')[0]}`], { queryParams: {id: 37, username: 'jimmy'}});

Summary:

this.router.navigate([ url ], { queryParams: { ... } })

Answer №2

When attempting to access a URL with query parameters, consider utilizing the router.navigateByUrl method for navigation.

For instance:

this.router.navigateByUrl('/page?id=37&username=jimmy');

Answer №3

Here is a suggestion:

Consider using the following approach:
this.router.navigate(['my-route', 37], { queryParams: { username: "jimmy"}});

Answer №4

this.router.navigateByUrl('/dynamicPage?id=37&name=jimmy');

Using dynamic parameters enhances the functionality of this method.

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

Inspect each chart for information and conceal any that are empty

Currently, I am attempting to analyze my highcharts graphs for data during loading and each redraw. I have successfully implemented the following code: (function (H) { var chartPrototype = H.Chart.prototype; // Display or hide graph based on da ...

Tips for maintaining the original Backbone template when reloading the browser

Within my Backbone application (with a Rails backend), I utilize [Handlebars] JavaScript templates (JST's) to render the Backbone views. However, whenever I refresh the browser while on a URL template, it always redirects me back to the root URL. I am ...

Validating CodeIgniter using advanced JavaScript techniques

When trying to insert data using a JavaScript and Bootstrap validation script, I encountered an issue. After entering a value in the text box, a warning pops up stating that the input value already exists. What should I modify in my script to address this ...

Secure Flask API used for serving JSON files to a basic HTML, JavaScript, and CSS web application

I have developed a basic web application that will display data in a table and be updated on a weekly basis. To perform this update, I utilize Python code in the backend to scrape and modify data before storing it in a SQLite database. After some researc ...

Grant permission to access a website even when domain filtering is enabled

I recently created a basic web application that utilizes the YouTube API for performing search and displaying results. $.ajax({ url: 'http://gdata.youtube.com/feeds/mobile/videos?alt=json-in-script&q=' + q, dataType: 'jsonp&apos ...

Tips for incorporating additional items into an established useState array utilizing map() or foreach()?

I'm working on developing a social media platform similar to Twitter, and I'm facing challenges with the news feed functionality. Essentially, the news feed is supposed to fetch tweets from my firebase database for each user followed by the curre ...

What is the best way to run multiple functions from an object?

My goal is to call all the functions that are contained within an object. const data = { fruits: funcA(), vegetables: funcB(), bread: funcC(), } The desired result looks like this: firstFunc(); dispatch(funcA()); dispatch(funcB()); dispatch(funcC() ...

Node.js Request Encoding Using Google Translate

I have developed a node.js module to use the Google Translate API. module.exports = function(sourceText, sourceLang, targetLang, callback) { var qst = qs.stringify({ client: 'gtx', sl: sourceLang, tl: targetLang, ...

AngularJS allows for the creation of 2D arrays using the $Index

Currently, I am working on a project using AngularJS that involves creating a spreadsheet from a 2D array generated by the ng-repeat function. As part of this project, I am developing a function to update the initial values of the array when users input ne ...

Using the onClick function to set attributes in React JS

I am currently working with 2 functions: addBookmark() and removeBookmark(). There is a variable called IsBookmarked that can be either true or false. In my JSX code related to bookmarks, it looks like this: {props.singleCompany.IsBookmarked ? ( ...

Utilizing one JavaScript file and consistent classes for multiple modals

Is it possible to have multiple modals using the same JS file, classes, and IDs? I created this code: <button id='myBtn'>Order/Discount</button> <div id='myModal' class='modal'> <div clas ...

Adjusting the height of the scrollbar in relation to a div using jScrollPane

I am currently working on a resizable div that utilizes custom scrollbars from jScrollPane. My goal is to position the vertical scrollbar above the resize handle. Is there a way to achieve this? I experimented with adjusting the verticalTrackHeight by al ...

What is the best way to position a static element next to a Vue draggable list?

I'm currently working on implementing a feature to display a list of draggable elements using vue-draggable. These elements are occasionally separated by a fixed element at specified position(s). My approach so far has involved creating a separate el ...

Is there a way to customize my website using JavaScript so that it is exclusively accessible to Windows users?

Is there a way to identify and block users of specific operating systems from accessing the site using JavaScript? if (navigator.appVersion.indexOf("Win") != -1) I am able to extract the user's OS using the provided code, but I need help in blocking ...

Is it possible for ng-repeat to change the index of an internal collection while reordering?

In my code, I am working with an array of objects: $scope.widgets = [{ col: 0, name: "Tile 1" }, { col: 1, name: "Tile 2" }, { col: 2, name: "Tile 3" }]; Each object from the array is displayed as a widget within a grid. When usin ...

Unveiling the secrets of extracting element content using JavaScript (with JQuery) from an HTML object

I have written the code below to access the page "JQueryPage.aspx" and retrieve data from it using jQuery: <script type="text/javascript> $.get ( "JQueryPage.aspx", function(data) { alert("Data Loaded: " + data); ...

Error: Attempting to access property 'baseHref' of an undefined value is not possible

Creating a webpack configuration for Angular 7 has been my recent project. I found a helpful tutorial on how to customize build configuration at this link. I decided to use the @angular-builders package for this task. Upon checking my index.html file, I m ...

What is the process of integrating data retrieved from an SQL query into a Pug template using Express and MySQL?

Currently, I am in the process of developing a basic web application that will initially show a list of bus route numbers and names upon landing on the page. My tech stack includes MySQL integrated with Express and Pug. Below is the server-side code snippe ...

Having trouble with my first Angular 2 application that is meant to print "My First Angular 2 App"?

I have created a program to display the message "My First Angular 2 App", but I am facing issues with the output. Can anyone help me identify where I might be going wrong? environment_app.component.ts import { AnotherComponent } from './anotherCompo ...

I attempted to publish my React application using gh-pages and encountered the following error: "The argument for 'file' must be a string. However, it was received as undefined."

I encountered an issue while attempting to deploy my React application with gh-pages. The error message I'm facing states: "The 'file' argument must be of type string. Received type undefined." Initially, I suspected that the problem was wi ...