Angular - 检查根路径 (/) 上是否存在 queryParams

问题描述 投票:0回答:1

我有一个用 Vaadin 编写的遗留应用程序,需要将其移植到 Angular 15,特别是使用相同的 URL 结构。我快完成了。缺少的一件事是我需要检查根路径上是否存在 no URL 查询参数。在这种情况下,我需要显示一个弹出窗口。

短:

  • http://xxx/?a=1234 <-- this is what the customer will get from the sales person
  • http://xxx/ <-- this should show a popup, like "wrong URL, contact sales"

我正在订阅

onInit
中的路线queryParams。我的第一次尝试是简单地检查参数是否存在于
subscribe
块中并以这种方式触发操作。这适用于没有 queryParams 的 URL,但如果参数存在,也会被触发。我将其简化,引入了一个计数器,并发现带有参数的订阅块实际上有两次迭代,第一次返回一个空对象。

这是正在运行的应用程序:

https://codesandbox.io/p/sandbox/xenodochial-rosalind-3mtpr5

订阅部分如下所示。如果它在

constructor()
:

中也是一样
  ngOnInit(): void {
    console.log('onInit start');
    this.route.queryParams.subscribe((p) => {
      console.log('count:' + this.count + ' => ' + JSON.stringify(p));
      this.params = p;
      this.count++;
    });
    console.log('onInit end');
  }

如果有查询参数,我会期望这样的结果:

onInit start
count:1 => { "a":"1234" }
onInit end

相反,我得到

onInit start
count:1 => {}
onInit end
count:2 => {"a":"1234"}

我尝试了几件事,但没有任何效果:

  • 将方块移至
    constructor()
  • 二手
    snapshot
  • 检查
    AfterViewInit()
    是否有最终结果
  • 试图找到一种方法来等待
    subscribe()
    完成
  • duckduck走了很多
  • ...

任何想法/提示都非常感谢。

angular routes url-parameters
1个回答
0
投票

Router

Observable
是 (BehaviorSubjects) 与 RxJS
Subject
可观察量不同。 这种可观察量首先给你一个初始值(什么是 null 或空对象)。

最简单的方法是跳过第一个值。

 this.route.queryParams.pipe(skip(1)).subscribe((p) => {
      console.log('counter:' + this.count + ' => ' + JSON.stringify(p));
      this.params = p;
      this.count++;
    });
© www.soinside.com 2019 - 2024. All rights reserved.