'How to capture query params in Angular app before showing any UI
I need to capture queryParam from URL http://localhost:4200/?user=123456 before showing any UI in my Angular application.
Actually I'm using this :
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
title = 'params-lab';
constructor(private route: ActivatedRoute) {
this.route.queryParams.subscribe(params => {
console.log('Params = ' + JSON.stringify(params));
});
}
ngOnInit() {
}
}
But in the dev console I'm getting for the first time Params = {} and then Params = {"user":"131245"}.
This way isn't what I'm expecting because I need to check if params are OK or not to redirect to the correct component like discribed below :
Solution 1:[1]
In two different ways u can solve this problem
- Send an additional param as uservalid = true from backend (easy solution but not efficient approach )
- Implement Route Guard with additional flags, where u can have concrete RBAC our the component.
https://codeburst.io/understanding-angular-guards-347b452e1892
Solution 2:[2]
Subscription in constructor will rarely return a value as fast as you want. Thus, introduce a var to keep the parameters:
parameters: string = null;
Then give it a value inside your constructor:
this.route.queryParams.subscribe(params => {
if (params) {
this.parameters = JSON.stringify(params);
// send parameters to method that will
// work with parameters, i.e. your logic to load
// different pages based on parameters value
}
});
You can put some loader content into app.component to be displayed until parameters are available through subscription:
<ng-container *ngIf="!parameters">
(loading content: text, image, spinner, whatever)
<ng-container>
Or just omit any html content.
Solution 3:[3]
ActivatedRoute gives you information about a route associated with a component that is loaded in an outlet. If you subsribe to the queryParams observable in your root component, you will see each and every change. As far as I understood you use case correctly, this is not what you want. I think you should register a separate component on your target route and put the redirect logic there.
RouterModule.forRoot([
{ path: '', component: RedirectComponent },
]),
and
class RedirectComponent implements OnInit {
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.queryParams.subscribe((params) => {
console.log('Params = ' + JSON.stringify(params));
if (/*...*/) {
// redirect from here
}
});
}
}
https://stackblitz.com/edit/angular-ivy-wjyejt?file=src/app/redirect/redirect.component.ts
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RED.Skull |
| Solution 2 | Misha Mashina |
| Solution 3 | hansmaad |

