我不知道天气是否正确?在我的应用程序中,有许多路由组件和功能模块。我想了解appcomponent.ts
文件或路由logincomponent.ts
首先执行哪个文件?
应用程序流FE将通过登录API调用通过BE进行通信(基于标头将切换到不同的组件)。如果登录成功,则将这些详细信息存储在一个全局导出对象中,这将作为服务注入到另一个组件中。
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 happaning
} 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'});
}
在这里,我的问题是哪个组件构造函数将首先调用。 appcomponent
或logincomponent
答案 0 :(得分:1)
通常,启动应用程序后,首先加载的是AppComponent
。
如果您查看自己的app.module.ts
,则其中应包含:
bootstrap: [ AppComponent ] // Means this gets loaded first
查看您的路由配置,您的AppComponent
将首先加载,然后路由会将您发送到LoginComponent
。