I am trying to write an Angular app that loads a different login page based on the "groupId" that I set in the URL. The idea is to send each client a URL that contains a particular "groupId" as a parameter. A template is used to load the page where the page's text and pictures are pulled from the firebase repo using that specific company's groupId.
I tried using query params as follows:
(In my component):
ngOnInit() {
console.log('test');
console.log(this.activeRoute.queryParams);
this.activeRoute.queryParams
.subscribe(params => {
this.groupId = params.groupId;
})
console.log(this.groupId);
if (this.groupId === undefined) {
this.router.navigate(['/login/locked']);
}
}
(and my routes in the parent component):
const routes: Routes = [
{
path: 'login',
component: LoginComponent,
children: [
{
path: '', component: SignInComponent,
},
{
path: 'signup', component: SignUpComponent,
},
{
path: 'locked', component: LockScreenComponent,
},
{
path: 'password-rest', component: PasswordResetComponent,
}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class AuthPagesRoutingModule { }
However, I keep on getting an undefined
from the console.log(this.groupId)
when I paste www.example.com/login?groupId='FACEBOOK235'
into the search bar (and thereby navigating me to the locked screen).
Am I missing something?
CodePudding user response:
because your if condition is outside subscribe and observables are asyncronous. your code should be :-
ngOnInit() {
console.log('test');
console.log(this.activeRoute.queryParams);
this.activeRoute.queryParams
.subscribe(params => {
this.groupId = params.groupId;
console.log(this.groupId);
if (this.groupId === undefined) {
this.router.navigate(['/login/locked']);
}
})
}
CodePudding user response:
Call to this.activeRoute.queryParams.subscribe
is not synchronous, therefore console.log keeps reporting undefined
. Add this check inside subscribe
, like so:
this.activeRoute.queryParams
.subscribe(params => {
this.groupId = params.groupId;
console.log(this.groupId);
if (this.groupId === undefined) {
this.router.navigate(['/login/locked']);
}
})
Also, you may like to check Guards - that's something you might need: https://angular.io/guide/router-tutorial-toh#milestone-5-route-guards . By adding CanActivate guard which returns true or URL tree, you'll achieve what you want.
CodePudding user response:
You subscribe an observable and they are asynchronous and your if condition outside the subscribe method so when you access your groupId propery you get undefined. you should access it in subscribe method.
ngOnInit() {
this.activeRoute.queryParams
.subscribe(params => {
this.groupId = params.groupId;
console.log(this.groupId);
if (this.groupId === undefined) {
this.router.navigate(['/login/locked']);
}
})
}