Will router links in Angular TypeScript ignore empty query parameters?

Below are the variables I am working with:

 inputCity;
 inputGuestNumber;
 inputCapacitySelected;
 inputCuisineSelected;
 inputPrivacySelected;
 inputVenueTypeSelected;
 inputAmenitiesSelected;
 inputNeighborhoodSelected;

These values may or may not have a defined value, depending on the user input in a form.

I have a function called router.navigate which sets query parameters. If any of these variables point to an undefined or empty value, what happens to the query parameters?

onSubmit(){
    this.router.navigate(['/venue-list', this.inputCity], {
        queryParams:{
           guestCount: this.inputGuestNumber,
           countOption: this.inputCapacitySelected,
           cuisineSelected:this.inputCuisineSelected, 
           privacySelected:this.inputPrivacySelected,
           venueTypeSelected: this.inputVenueTypeSelected,
           amenitiesSelected: this.inputAmenitiesSelected,
           neighborhoodSelected: this.inputNeighborhoodSelected
        }
  });

Thank you!

Answer №1

Query parameters are additional parameters that are not required to determine the route to a component. However, if you pass query parameters with undefined variables, it can lead to a request like the following:

localhost:3000/venue-list/:inputCity?guestCount=2&countOption=undefined&cuisineSelected=anyvalue&privacySelected=undefined

Empty query parameters will not be disregarded. So when the venue-list component is opened,

ngOnInit() {
    this.sub = this.route
      .queryParams
      .subscribe(params => {
        this.guestcount = +params['guestCount'];
        this.countoption = +params['countOption'];<- in this.countoption you will get undefined
      });
  }

It would be more effective to assign default values to all query parameters in case some of them are undefined, like so:

subscribe(params => {
    // Assigns 0 as default value if no query param is provided.
    this.guestcount = +params['guestCount'] || 0;
    this.countoption = +params['countOption'] || default_value;
  });

Alternatively, you can use an if condition to check for undefined values.

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

Instruct Vue to scan through a directory full of images without altering the filenames of the images

I came up with a method to instruct Vue to search in a file and assign images to the corresponding number of cards. So far, it's working perfectly. However, I'm curious if there is a more efficient way to achieve this. The current drawback is th ...

JQuery Mobile: Adding fresh, dynamic content - CSS fails to take effect

I've encountered this issue before, but I'm still struggling to resolve it. When adding dynamic content to a page (specifically a list-view), the CSS seems to disappear once the content is added. I've tried using the trigger("create") functi ...

Tips on transforming a JSON file into a response for my personal server

After successfully converting an Excel file to JSON format using my code, I encountered a challenge when trying to convert this as a response. Despite attempting to use res.send in the JS code, it only displayed directory/inner codes instead of a response. ...

What steps should I follow to set up a React + Node server on a local network?

My goal is to set up a local network with both a React server and a Node server. The website contains multiple pages and utilizes axios for sending and receiving data from the node server. Additionally, I have configured a proxy in the package.json file to ...

Reduce the size of your Javascript files to the earliest possible version

Any suggestions for converting minimized JavaScript to earlier versions? Are there any tools or websites available for this task? Thank you in advance for any hints. ...

Displaying the value of HTML in JavaScript is not possible

When attempting to use JavaScript to alert the selected textarea value, I encountered a problem. My code $("#kandungan_email").html(); is unable to capture the &#13;&#10; characters within the HTML content. Here is the snippet of my code ...

The UNHANDLEDREJECTION callback was triggered prematurely during asynchronous parallel execution

Asynchronously using parallel to retrieve data from the database in parallel. Upon each task returning the data, it is stored in a local object. In index.js, the cacheService.js is called. Inside cacheService.js, data is loaded from both MySQL and MongoDB ...

Finding the mouseover event for an element that is beneath an overlaid div

There are four div elements, and on mouseover, the selected div will get zoomed. However, I also need to capture the mouseover event for the remaining three underlying divs, even when one is overlayed. This way, I can zoom out the previously selected div a ...

Creating the Apk file for your sencha touch application

Hello there! I'm diving into the world of Sencha Touch as a new user. After installing all the required tools and SDK, I successfully set up the demo example that came with project creation via command line. Now, I'm eager to generate the APK fil ...

Every piece of data entered in Next.js triggers a complete refresh

Currently, I am developing a Next.js application using version 12.1.5. However, I have encountered a perplexing bug. Every input component triggers a full re-render with each keystroke, causing the input to lose focus. This issue persists across various co ...

Incorporate the authorization button into Swagger Documentation using NodeJS

I am looking to integrate a button in Swagger's UI interface that allows testers to easily add the "Bearer token" header and conduct API testing. https://i.sstatic.net/Dyxdc.png The configuration for my Swagger setup is as follows: module.exports = ...

When the bounds are adjusted, removing markers in Vue Cookbook's Google Map

I've encountered an issue with clearing markers after updating new bounds on a map. Whenever I post a request with new bounds, new markers get added to the map while the old ones remain in place. This situation becomes quite awkward for me because the ...

[JSP Tutorial] Step-by-step guide to create a basic sorting algorithm

Hello, I need assistance with coding a list of years that are displayed as shown below: YEAR ==== 2014 2013 2012 Here is the corresponding code snippet: <script type="text/javascript"> jQuery(document).ready(function() { }); </script> ... ...

What is the significance of receiving an error in Internet Explorer when running the code below?

function checkStepValidity(isValid, dataModel) { if (isValid) { updatedDataModel = mergeObjects(this.updatedDataModel, dataModel); } }, The code above encounters the following error in Internet Explorer / Edge browse ...

Is there a way to manipulate my csv values so that they all appear in a single column?

I've been using the ngx-papaparse library to convert an array into a CSV file. However, after downloading the CSV file and opening it with Excel, I noticed that my values are not appearing in the correct columns. This is the function I am using: dow ...

Fade effect not working with Bootstrap Modal

I am encountering an issue with the Twitter Bootstrap modal while trying to display post details on WordPress. The problem is that when the modal opens, the entire screen turns grey and nothing in the modal is clickable. I can only exit this mode by pressi ...

Javascript problem with closing the browser window in Selenium WebDriver

Here are a couple of inquiries: Firstly: Is there a method to initiate the browser on a specific URL (instead of about:blank) while also setting the history length to 0 when starting on that URL? Secondly: I suspect this question is related to the one me ...

How does 'style' compare to 'insertRule/addRule'?

Can you identify the distinction? What is the most effective approach to tackle this issue? let stylesheets = document.styleSheets[0]; stylesheets.addRule('div::before','content:"text before";'); stylesheets.addRule('#some', ...

Is it possible to utilize AJAX to fetch code from a separate file, view, or page in order to create an experience akin to a single-page application

Essentially, I'm aiming to create a simplified version of a Single Page Application within the admin panel of my website. The idea is to organize the information by using tabs, making the panel less cluttered. Here's a rough layout of what I have ...

How to transfer a user's comment from HTML to a C# model through a list within the MVC framework

I have been attempting various solutions, but none seem to be working. My goal is to create post and comment partial classes for a main page where end users can add comments. Currently, I am using MVC 5 and the page loads posts and previous comments. Howe ...