【问题标题】:How to capture queryParams on page load in Angular 10?如何在 Angular 10 中捕获页面加载时的 queryParams?
【发布时间】:2020-12-09 17:38:54
【问题描述】:

在我们的应用程序中,我们通过 ?token=[TOKEN] 查询参数为用户设置恢复过程。 设置新密码的链接指向项目的主页,如下所示:

https://our-project.com?token=[TOKEN]

在应用程序加载过程中,有一个 RedirectRoleGuardService,它只是检查用户是否 经过身份验证,如果是,则将用户重定向到特定路线。代码如下:

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    return this.store.pipe(
      select(fromAuth.selectRole),
      tap((role) => {
        if (role)
          this.router.navigate([state.url + '-' + role], { queryParamsHandling: 'preserve' }).then()
        else
          this.router.navigate(['/main-unauth'], { queryParamsHandling: 'preserve' })
            .then()
      }),
      take(1),
      map(() => true)
    )
  }

如您所见,我尝试使用 queryParamsHandling,但效果为零。 QueryParams 根本不保存。

期望的行为: 我希望能够在页面加载期间捕获 queryParams。 URL:https://our-project.com?token=[TOKEN],我想捕获带有值的 ?token 并将其传递给由 RedirectRoleGuardService 重定向的 url

【问题讨论】:

    标签: angular angular-router


    【解决方案1】:

    我目前正在使用 Angular 7,不确定我是否完全理解您的要求,但让我们试一试。如果我没有错,请尝试以下操作:

    ngOnInit() {
        const queryStr = window.location.search;
        if (queryStr) {
            const urlParams = new URLSearchParams(queryStr);
            const tokenFromUrl = urlParams.get('token');
            console.log("tokenFromUrl", tokenFromUrl);
            if (tokenFromUrl) {
                //do something
            }
            else {
                //redirect to Homepage
            }
        }
    }
    

    更新:经过一番研究,我发现它已被弃用,根据What is the replacement for Angular @angular/http URLSearchParams class in Angular 5,您可能应该使用HttpParams 来获取token 的值。

    【讨论】:

    • 感谢您的回答。这是传递令牌参数的一种工作方式。我想可能是我的应用程序需要传递所有查询参数,而不仅仅是一个令牌。你会怎么做?我很遗憾 queryParamsHandling: 'preserve' 在 canActivate 防护中不起作用。那将是完美而清晰的解决方案。查看 location.search 查询参数可用,为什么 queryParamsHandling 不起作用?
    • 不客气。如果您知道所有参数,为什么不这样做呢?例如,如果 url 是 https://our-project.com?token=[TOKEN]&amp;param1=[PARAM1]&amp;param2=[PARAM2],请尝试将它们设置为 urlParams.get('token')urlParams.get('param1')urlParams.get('param2') 等。很抱歉,我无法为您提供 queryParamsHandling 及其工作原理的帮助。
    【解决方案2】:

    //你可以在app组件的ngOnInit函数中使用这个来获取queryParams

        const url = window.location.href;
        if (url.includes('?')) {
           const httpParams = new HttpParams({ fromString: url.split('?')[1] });
           const token = httpParams.get("token");
        }
    

    【讨论】:

      【解决方案3】:

      你可以在ngOnInit试试这个方法

      // URL: localhost:4200/list?module=cars
      
      this._route.queryParams.subscribe(params => {
              //params is an object
              const ParamLabels = Object.keys(params);
      
              // validate the queryParams otherwise redirect to dashboard
      
              if (!ParamLabels.includes('module')) this._router.navigate(['../dashboard']) 
              if (params['module'] == undefined) this._router.navigate(['../dashboard'])
              if (params['module'] == '') this._router.navigate(['../dashboard'])
      
              // some fn here
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-09
        • 1970-01-01
        • 1970-01-01
        • 2015-07-12
        • 1970-01-01
        • 2016-07-07
        相关资源
        最近更新 更多