Uncertainty surrounds the correctness of my question. Within my application, there exist numerous routing components and feature modules. I am eager to discern whether the appcomponent.ts
file or the routing logincomponent.ts
file will be executed first.
As the flow of the application shifts from the frontend to the backend through a login API call (changing components based on headers), successful logins prompt the storage of pertinent details within a globally exported object, subsequently injected as a service into another component.
appcomponent.ts
constructor(private auth: AuthService, private user: User) {
this.auth.login().subscribe((res)=>{
this.user.userProps.userRole = resp.headers.get('userRole');
})
}
app.routing.module.ts
{ path: '', pathMatch: 'full', redirectTo: '/login' },
{ path: 'login', component: LoginComponent, canActivate: [RandomGuard] }
random.guard.ts
canActivate() {
console.log(this.user.userProps); // have null value; why app component value not receiving here
if (this.user.userProps.userRole === 'user') {
this.router.navigate(['/user']);
} else if (this.user.userProps.userRole === 'admin') {
this.router.navigate(['/admin']);
}
return true; // So it will redirect into login
}
login.component.ts
constructor(private user: User, private auth: AuthService, private router: Router) {
if (this.user.userProps.userRole === '' || this.user.userProps.userRole === null) {
this.auth.login().subscribe((resp: any) => {
console.log(resp, 'resp');
this.user.userProps.userRole = resp.headers.get('userRole');
if (this.user.userProps.userRole === 'admin') {
this.router.navigate(['/admin']); //proper routing will happen
} else {
this.router.navigate(['/user']);
}
}, (err) => {
return false;
});
}
}
auth.service.ts
login(): Observable<HttpResponse<any>> {
return this.http.get(`${environment.baseUrl}home/login`, {observe: 'response'});
}
My query pertains to which component's constructor gets invoked first - appcomponent
or logincomponent
.