Creating a Query String in a web URL address using the state go method in Angular State Router

On my product list page, there is a list of products. When I click on a particular product, a function is called that uses state.go.

Issue with dynamic functionality:

$state.go('home.product.detail', { 'productID': "redminote4", 'brand': 'x', "store":"amazon" });

.state('home.product.detail', {
    url: '/products/:?productID?brand?store',
    views: {
        '@': {
            templateUrl: baseUrl + 'products/products',
            controller: 'productsController'
        }
    },
    data: {
        displayName: '',
        displayImg: 'Images/productsHeaderIcon.png'
    }, resolve: {

        param2: function (LoginHome) {

            return LoginHome.getHomeService1();

        }
    }

**

The expected web URL output should be:
productID=redminote4&brand=amazon&store=amazon:

Another issue is that the value is retrieved in stateparams: e.g.) stateparams.productId=redminote but the URL is not constructed **

Functioning correctly:

When I set the values in the params, I am able to get the desired output URL as mentioned above:

**function call:**

$state.go('home.product.detail', { 
'productID': "redminote4", 'brand': 'x', "store":"amazon" });

App:

 .state('home.product.detail', {
  url: '/products/:?productID?brand?store',
params:{
'productID': "redminote4", 
'brand': 'x', 
"store":"amazon" }

},
        views: {
            '@': {
                templateUrl: baseUrl + 'products/products',
                controller: 'productsController'
            }
        },
        data: {
            displayName: '',
            displayImg: 'Images/productsHeaderIcon.png'
        }, resolve: {

            param2: function (LoginHome) {

                return LoginHome.getHomeService1();

            }
        }

Why is the URL not being formed dynamically?

Answer №1

Your URL parameters are not correctly defined. However, you can utilize lifecycle methods to return a target instead.

.state('home.product.detail', {
    url: '/products/?productID&?brand&?store',
    params:{
        'productID': {
            value: "redminote4", 
            squash: true
        }
        'brand': {
            value: "x", 
            squash: true
        }, 
        'store': {
            value: "amazon", 
            squash: true
        }
},
data: {
    displayName: '',
    displayImg: 'Images/productsHeaderIcon.png'
},
onEnter: ['$transition$', '$state$', 'LoginHome', function(transition, state, LoginHome){

    if(!transition.options().resolvedParams){
       return transition.router.stateService.target(
                 transition.to().name, 
                 {
                    productID: 'redminote4', 
                    brand: 'x', 
                    store:'amazon'
                 },
                 { 
                    resolvedParams: true 
                 }
           );
        }
    }]

This approach stops the state change and substitutes it with your new target that includes your parameters. I am using a custom key in the options object to prevent redirecting the state change again in this example.

For more information about the lifecycle, check here, and learn about the returned TargetState here

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

Propagating numerical values through iterative iterations

I am currently facing an issue with passing values as props to a component using the forEach method in JavaScript. In addition to passing the existing values from an array, I also want to send another value that needs to be incremented by 1 for each iterat ...

An unexpected error occurred during page generation. Any relevant console logs will be shown in the browser's terminal window

Encountered a RangeError: Maximum call stack size exceeded while compiling this web app in the browser. The error occurred on my header tag and sometimes on the return tag. What should I do? export default function Header() { return ( <> ...

SharePoint 2013 only allows the first AJAX request to work successfully, except when in Edit Mode

I am facing a challenge of making two AJAX requests simultaneously on a SharePoint page. One request originates from the current site, while the other comes from a team site. When I use different URLs (/events) and (/travel), each one works fine when use ...

Is there a way to trigger the interval on the second load and subsequent loads, rather than the initial load?

I have implemented the use of setInterval in my recaptcha javascript code to address the issue of forms being very long, causing the token to expire and forcing users to refill the form entirely. While I am satisfied with how the current code functions, t ...

Using the find() function in Mongoose allows the use of a variable as a model

Would it be feasible to employ a variable in place of the model name when using the find() function in mongoose? For instance, if my website is capable of displaying photos and videos based on the last part of the URL, which could be either /photo or /vide ...

As soon as a key is pressed in tinyMCE, the tracking continues until reaching the conclusion of the initial <

I am attempting to capture, in real-time, the user input in the .content textarea and paste it into the .intro. I have tried the following code without success: //This code is specifically for tinymce, as I am using tinyMCE as a rich text editor for textb ...

Adding multiple elements with varying content to a separate division

I am attempting to combine two div elements into a single div, but I'm encountering difficulties. Despite thoroughly examining my code, everything appears to be correct. Here's what I've tried so far. To assist me in achieving this, I am ut ...

Acquiring the asset within the controller

Having trouble accessing my service within the controller. This project was generated with the latest yeoman which handles template creation and file merging during build. Whenever I make changes, Angular stops working without displaying any errors in the ...

The $.each function seems to be stuck and not cycling through the

Dealing with a rather intricate JSON structure, I'm encountering difficulty iterating through it using the $.each() function. It seems to be related to the unusual 2-dimensional array passed in the value section of the standard array (hopefully that m ...

What is the best way to insert events into your Google Calendar directly from a website?

Looking for some help with integrating Google Calendar and adding event features to my HTML page. I've successfully embedded the calendar onto my website, but I'm struggling to add events directly from the webpage. Is there a way to make this fea ...

Enhance the angular 2 dependencies within the angular2-cli project

After experimenting with Angular 2 and following the guide on their website, I attempted to switch to Angular 2 CLI. However, the Angular 2 CLI project does not have the latest dependencies, resulting in errors from the compiler related to certain commands ...

Unable to `.catch()` an error while utilizing Jquery.ajax().then()

My current project involves making calls to various APIs using JQuery and caching the response from each API. This cached data is then used multiple times on the page to create different dashboard widgets. The issue I'm facing is that if an API retur ...

Encountering a problem with vis js events

While constructing a timeline in my vue.js application, I opted to utilize vis.js. Unfortunately, I encountered some issues when attempting to incorporate events. Initially, setting @drop="myDropCallback()" did not trigger the function upon dropping an ite ...

Ways to dynamically assign value to a checkbox using jquery

var sites = sites_str.split(","); $.each(sites,function(i,j) { $('.check').append("<input type=checkbox name=site_name value=sites[i]>"+sites[i] +"</br>" }) I am facing an issue when trying to retrieve the values of selected check ...

Unable to retrieve value - angularJS

An AngularJS application has been developed to dynamically display specific values in an HTML table. The table consists of six columns, where three (Work Name, Team Name, Place Name) are fixed statically, and the remaining three columns (Service One, Servi ...

Issue: Node Sass 8.0.0 is not compatible with the version ^4.0.0

I encountered an error when starting a React app with npm start. How can I resolve this issue? ./src/App.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--6-oneO ...

What could be causing the "Error - Only secure origins are permitted" message to appear for my service worker?

Whenever I attempt to implement a service worker on my progressive web application page, why does the browser console display this specific error message? ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed JavaScript Code: ...

Creating interactive tables in JavaScript with dynamic row adding, editing and deleting capabilities

Whenever I try to add a new row by clicking the Add Row button, an error occurs. My goal is to append a new 'tr' every time I click the add row button. Each 'td' should include a checkbox, first name, last name, email, mobile number, ed ...

Maximizing the benefits of AngularJS $routeprovider resolve functionality while maintaining a seamless loading experience for the user

After reading multiple articles on the $routeprovider resolve feature, my interest was piqued by a repository created by one of my favorite AngularJS developers, Todd Motto. You can check out his work at https://github.com/toddmotto/angularjs-styleguide#co ...

ng-class in Angular seems to be functioning properly on <td> elements, but is not

When using this HTML inside an ng-repeat, there is a difference in behavior: This part works fine: <tr> <td ng-class="info.lastInMonth">{{ info.date_formatted }}</td> ... But this section does not work as expected: <tr ng ...