【问题标题】:URL changed but component was not rendered. Just work correctly after reload pageURL 已更改,但未呈现组件。重新加载页面后才能正常工作
【发布时间】: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.tsrouterLink

感谢任何帮助

【问题讨论】:

  • 我更新了这篇文章。当我在 Navbar 中单击 Profile 并且 user 被正确记录时,我还测试了日志用户
  • 控制台有什么错误吗?
  • 不,先生。我把控制台登录到AuthGuardUserComponent,点击后我在控制台中只看到'Auth guard working'。然后我重新加载页面,我看到“验证保护工作”和“用户组件初始化”

标签: angular routes


【解决方案1】:

您的app.component.html 应如下所示:

<div *ngIf="isLoggedIn">
    <app-navbar></app-navbar>
</div>
<router-outlet></router-outlet>

&lt;router-outlet&gt; 应该在启动时加载。

【讨论】:

  • &lt;router-outlet&gt; 应该在外面,在启动时
猜你喜欢
  • 2021-05-02
  • 2019-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多