【问题标题】:Router-Outlet Navigation With Constant Sidebar and NavBar on AngularAngular 上带有恒定侧边栏和导航栏的路由器插座导航
【发布时间】:2019-11-25 04:21:19
【问题描述】:

对于如何放置路由器插座,我有点困惑。我曾尝试研究类似的案例,但无济于事。 这是场景 我有一个仪表板组件,它在登录成功后加载。仪表板包含在 html 上声明的侧边栏、页脚和导航组件。现在,当我单击用户链接向我显示用户列表时,它会加载用户组件,但侧边栏、页脚和导航消失了,我只剩下用户组件。我只是想要一种情况,当我点击侧边栏中的链接时,它只是更改内容而不删除侧边栏、页脚和导航...... PS:用户组件有自己的模块,然后我像往常一样将它导入到 appModule 中。

这是我目前所拥有的。

app.component.html

<router-outlet></router-outlet>

dashboard.component.html

<side-bar></side-bar>
<topnav-bar></topnav-bar>
<content></content>
<footer></footer>

sidebar.component.html

 <li>
            <a id="formsli" (click)="anchorClicked($event)"
              ><i class="fa fa-user"></i> User<span class="fa fa-chevron-down"></span
            ></a>
            <ul class="nav child_menu">          
              <li><a [routerLink]="['/user/list']">User List</a></li>
              <li><a [routerLink]="['/user/new']">New User</a></li>
            </ul>
 </li>

用户路由文件

const routes: Routes = [
    { path: 'user/list', component: UsersComponent },
    { path: 'user/new', component: UserComponent },
];

应用模块

export const AppRoutes2: Routes = [
  { path: '', component: LoginComponent},
  { path: 'content', component: ContentComponent },
  { path: 'dashboard', component: DashboardComponent },
];

imports: [
      BrowserModule,
      RouterModule.forRoot(AppRoutes2, {useHash: false}),
      HttpClientModule,
      UsersModule,
   ],

如果我单击用户列表链接,侧边栏、导航和页脚就会消失。我希望它保留并只更改内容区域。

请问,我做错了什么或做错了什么??

【问题讨论】:

  • Well Router Outlet 将组件替换为加载的任何组件。因此,如果导航栏和侧边栏不是用户组件的一部分,那么它们将不会被加载。您可以做的是将它们全部加载到应用程序组件中,无论是在单独的共享组件中,还是单独或一个一个地加载,并且仅当用户在路由器出口之外登录时才使用 ngif 指令显示或隐藏公共组件

标签: angular angular-ui-router


【解决方案1】:

App.component.html

     //use the ngIf directive to either create or destroy the div with       static content (this is determined from the app.component.ta
      <div class='user-nav' *ngIf="isLoggedIn">
          <side-bar></side-bar>
          <top-navbar></top-navbar>
       </div>
     //anything that is routed will show up here
       <router-outlet></router-outlet>
    //if you want the footer to only be available after logging in add it here too
       <footer></footer>

【讨论】:

  • 感谢您的反馈。我有点理解你这里的逻辑。但是在登录页面有自己的组件并且应用程序和登录组件之间没有关系的情况下。那么如何在渲染其 html 之前更新应用组件 ts 文件中的属性“isLoggedIn”的最佳方法是什么?
  • 这取决于您登录用户的策略,尽管我对两者之间没有关系感到困惑,因为应用程序组件是引导组件。如果您使用本地存储来存储会话状态,您可以从那里查找它,但大概您有某种服务可以让用户登录,该应用程序组件可以访问。
  • 是的,计划在登录成功后使用本地存储来存储用户的令牌,以便我可以在需要时轻松获取用户数据...也许我将创建一个函数来简单地跟踪loggedInUser .....看起来很有希望。
  • 你也可以从应用程序组件访问本地存储,如果它是一个有效的令牌,那么你可以说用户已登录,我的存在通常是有一个在整个应用程序中始终可见的 topnav检查网站启动时用户是否已登录。使用 observable 我可以跟踪登录状态,而无需返回本地存储。
  • 谢谢,我也会考虑到这一点。再次感谢您的想法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多