【发布时间】:2020-10-04 07:54:50
【问题描述】:
我的路由模块设置
app-routing.module.ts
{
path: '', pathMatch: 'full', canActivate: [AuthGuard],
component: HomeComponent,
},
{
path: 'profile', component: ProfileComponent, canActivate: [AuthGuard],
children: [
{
path: 'edit', component: EditComponent
},
{
path: ':username', component: UserComponent
}
}
Profile.component.html
<router-outlet></router-outlet>
在我成功登录我的应用程序后,服务器响应一个用户,我使用BehaviorSubject 发出新用户
在导航栏组件中,我订阅并将其存储到属性 user
身份验证服务
user = new BehaviorSubject(null)
login() {
this.http.post('/api/login', {username, password})
.subscribe((userResponse) => this.user.next(userResponse))
}
App.component.html
<div *ngIf="isLoggedIn">
<app-navbar></app-navbar>
<router-outlet></router-outlet>
</div>
<div *ngIf="!isLoggedIn">
<router-outlet></router-outlet>
</div>
App.component.ts
isLoggedIn: boolean = false;
ngOnInit() {
this.authService.user
.subscribe((user) => {
if (user === null) {
this.router.navigate(['/login']);
this.isLoggedIn = false;
}
else {
this.isLoggedIn = true;
}
})
}
Navbar.component.html
<a routerLink="/" class="pt-3 pb-3 pl-4 pr-4 active">Home</a>
<a [routerLink]="['/profile', user.username]" class="pt-3 pb-3 pl-4 pr-4">Profile</a>
问题是当我点击 Profile 时,地址栏中的 url 按预期更改为 /profile/abc,AuthGuard 也正常工作并返回 true,但 UserComponent 是未渲染。我仍然留在HomeComponent
但是,当我按 F5 页面时,加载的 UserComponent 和导航栏路由完美运行。
我认为问题出在我的App-routing.module.ts 或routerLink
感谢任何帮助
【问题讨论】:
-
我更新了这篇文章。当我在 Navbar 中单击 Profile 并且 user 被正确记录时,我还测试了日志用户
-
控制台有什么错误吗?
-
不,先生。我把控制台登录到
AuthGuard,UserComponent,点击后我在控制台中只看到'Auth guard working'。然后我重新加载页面,我看到“验证保护工作”和“用户组件初始化”