Modify query param in url with angular application

82 Views Asked by At

I have a small mini game in which the input is a random number, so it would be something like that:

http://localhost:4200/minigame

In order to that mini game to be "repeatable" I want to add like a seed.

So you could also add the seed to the url like this:

http://localhost:4200/minigame?seed=123

In case the queryparam seed is not passed, I want to generate it randomly, and add it to the query param, so the workflow would be like this:

 1. Go to http://localhost:4200/minigame
 2. Because there is no seed passed, the angular components generates one, as an example seed=123
 3. The seed query parameter is addded to the url: http://localhost:4200/minigame?seed=123

is it possible to do that?, to modify the query parameter, or I would need to generate the seed, and then redirect to minigame?seed=123

1

There are 1 best solutions below

0
Nikhil Makwana On

You can access and modify the query parameters of the current URL using the ActivatedRoute service. You can use this service to check if a seed parameter is present in the URL, generate a random seed if it's not, and then update the URL with the seed parameter.

example:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-minigame',
  templateUrl: './minigame.component.html',
  styleUrls: ['./minigame.component.css']
})
export class MinigameComponent implements OnInit {

  seed: number;

  constructor(private route: ActivatedRoute, private router: Router) { }

  ngOnInit() {
    // Check if the seed parameter is present in the URL
    this.route.queryParams.subscribe(params => {
      if (params.seed) {
        // If seed parameter is present, use it
        this.seed = +params.seed; // Convert to number
      } else {
        // If seed parameter is not present, generate a random seed
        this.seed = Math.floor(Math.random() * 1000); 

        // Update the URL with the generated seed
        this.router.navigate([], {
          relativeTo: this.route,
          queryParams: { seed: this.seed },
          queryParamsHandling: 'merge'
        });
      }
    });
  }
}