How to retrieve queryParams passed to an Angular route via NavigateByUrl

1.2k Views Asked by At

How to retrieve params passed as NavigationExtras using navigateByUrl as described below from the target component in Angular ?

let extras: NavigationExtras = {
                queryParams : {
                    errorTitle: 'Erreur Technique',
                    errorBody: 'URL erronée'
                }
            };
this.router.navigateByUrl(RoutesUrl.ERROR, extras);
2

There are 2 best solutions below

0
Ghassen On BEST ANSWER

The solution that I found is suggested by soulfresh in this GitHub issue : https://github.com/angular/angular/issues/18798

I call my route this way :

this.router.navigateByUrl(this.router.createUrlTree([RoutesUrl.ERROR], {
                queryParams: {
                    errorTitle: 'Erreur Technique',
                    errorBody: 'URL erronée'
                }
}));

then I retrieve query params this way :

this.activatedRoute.queryParamMap.subscribe(params => console.log(JSON.stringify(params)))

or

this.activatedRoute.queryParams.subscribe(params => console.log(JSON.stringify(params)))

UPDATE

If you don't want that your queryParams appears in the address bar (URL) you can use :

Sending data :

constructor(private router: Router) {} 

ngOnInit(){
    this.router.navigate([RoutesUrl.ERROR], {
                    state: {
                        errorTitle: 'Erreur Technique',
                        errorBody: 'URL erronée'
                    }
    });
}

Retrieving data :

constructor(private router: Router) {
      this.errorTitle = this.router.getCurrentNavigation().extras.state.errorTitle;
      this.errorBody = this.router.getCurrentNavigation().extras.state.errorBody;
  }
1
HassanMoin On

You can use the Activated Route by injecting it into your component.

 constructor( private activatedRoute: ActivatedRoute  ) {}

 ngOnInit(): void {
     this.activatedRoute.queryParams.subscribe((params: Params) => {
        this.params = params;
    });
 }

Or you can get the queryParams from its activated routes' snapshot

 ngOnInit(): void {
    const params = this.activatedRoute.snapshot.queryParams;
    console.log(params.errorTitle);
    console.log(params.errorBody);
}