我有一个小游戏,其中输入是一个随机数,所以它会是这样的:
http://localhost:4200/minigame
为了使该迷你游戏“可重复”,我想像种子一样添加。
所以你也可以将种子添加到网址中,如下所示:
http://localhost:4200/minigame?seed=123
如果查询参数种子没有通过,我想随机生成它,并将其添加到查询参数中,所以工作流程将是这样的:
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
可以这样做吗?修改查询参数,或者我需要生成种子,然后重定向到小游戏?seed=123
您可以使用ActivatedRoute服务访问和修改当前URL的查询参数。您可以使用此服务检查 URL 中是否存在种子参数,如果不存在则生成随机种子,然后使用种子参数更新 URL。
示例:
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'
});
}
});
}
}