如何从Angular中的app组件中的ActivatedRoute快照获取查询参数?

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

我希望同步获得app.component中的查询参数,而不是使用ActivatedRoutequeryParamMap observable。出于这个原因,我使用路由快照如下:

const param = this.route.snapshot.queryParamMap.get('param');

这适用于子组件,但似乎不适用于app.component。这是一个StackBlitz

是什么原因以及如何达到预期效果?

angular routes snapshot query-parameters
1个回答
0
投票

问题是你正在访问路线的快照。在app-component运行初始化阶段时,该值为null。

如果您的子组件已创建,而路由已经发生,则快照可能会在导航后为您提供正确的queryParam。但是,例如,如果您在深层链接中并且尝试刷新页面,则即使在您的子组件中,快照也可能为空。

要在那里访问routeParam,您需要实际订阅queryParamMap或queryParams。就像是:

this.route.queryParamMap.pipe(map((paramMap: ParamMap) => {
      return paramMap.get('param');
    }), distinctUntilChanged()).subscribe(val => {
      this.param = val;
      // having changedetection.onPush activated you would need to call the 
      // cdR.markAsChecked() here
    })

也许这有帮助:Angular Router: Understanding Router State

© www.soinside.com 2019 - 2024. All rights reserved.