Search code examples
angularangular-router

Why queryparamshandling: "preserve" is not working as expected?


Friends, I am stuck with queryParamsHandling parameter that is not working as expected. In my app i have a redirect service that is simply checking user role by using selector and depending on role redirects to specific urls. Code is below. What i want is just to save queryParams and redirect holding them on different route as well. I found out that queryParamsHandling is just for that. But it always flushes all queryParams on the redirected URL. I want initial url like: http://main-page.com?param1=500 after redirect to be http://main-page-unauth.com?param1=500 still hold query param1. And that applied no matter how many queryParams is there - 1,2,3...1000

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, ActivatedRoute } from '@angular/router';
import { Observable  } from 'rxjs';
import { select, Store } from "@ngrx/store";
import * as fromAuth from "../reducers";
import { map, take, tap } from "rxjs/operators";
import { HttpParams } from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class RedirectGuardService implements CanActivate {

  constructor(
    private router: Router,
    private store: Store<fromAuth.State>,
    private activatedRoute: ActivatedRoute
  ) {
  }

  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]).then()
        else 
           this.router.navigate([ '/main-unauth'], { queryparamshandling: 'preserve' })
            .then()
      }),
      take(1),
      map(() => true)
    )
  }
}

I even debugged that piece of code and can clearly see when queryparamshandling is being checked. In that moment currentUrlTree is always null.

case 'preserve':
    q = this.currentUrlTree.queryParams;
    break;

How do i save queryParams and pass it to redirected URL? Thanks

UPDATE: queryparamshandling works as expected in components (when app is loaded). The problem is that i am trying to use it inside canActivate proccessing. How do i pass queryParams in this situation ?


Solution

  • queryParamsHandling is not working during canActivate guards. If you want to preserve queryParams you need to manually pass queryParams using ActivatedRouteSnapshot

    https://stackoverflow.com/a/45843291/372212

    Solution is working. And it also has an explanation.