我的路由模块设置
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>
问题是,当我单击“配置文件”时,地址栏中的URL会按预期更改为/ profile / abc, AuthGuard 也可以正常工作并返回true,但 UserComponent 没有呈现。我仍然留在 HomeComponent
但是,当我按F5键时,UserComponent已加载且导航栏路由正常运行。
我认为问题出在我的App-routing.module.ts
或routerLink
感谢您的帮助
答案 0 :(得分:2)
您的app.component.html
应该如下所示:
<div *ngIf="isLoggedIn">
<app-navbar></app-navbar>
</div>
<router-outlet></router-outlet>
<router-outlet>
应该在启动时加载。