Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

angular - Redirection using routing module

I have a login page and after login in I am redirecting to a dashboard. The dashboard has some children pages also. I need that when you be logged in and click in the logo I be redirected to the dashboard and if I am not logged in I be redirected to the login page. Here is an example of my code:

navbar.component.html

<mat-toolbar>
    <h1>
      <a routerLink="/">
        <img src="../image.jpg"/>
      </a>
    </h1>
  </mat-toolbar>

routing.module.ts

.
.
.
const routes: Routes = [
  {
      { path: '', redirectTo: 'login', pathMatch: 'full' },
      {
        path: 'login',
        component: ClientLayoutComponent,
        children: [
          { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
          {
            path: 'dashboard',
            component: DashboardComponent,
            canActivate: [DashboardGuard],
          },
          {
            path: 'account',
            component: AccountComponent
          },
          { path: 'Blog', component: BlogComponent },
        ],
      },
  },
];

The steps are so clear:

  1. If I am not logged in, when I click in the logo it have to go to login page or,
  2. If I am logged in, when I click in the logo it have to go to dashboard page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would separate the login path and the dashboard path. If you want to deny access to the dashboard (if not logged in) I would suggest to use a route guard.

A fast (dirty) way to do it is to create two logo links and serve the correct one based on if the user is logged in or not:

e.g:


# in the component, create an variable that holds the value if a user is logged or not

<a *ngIf="userIsLoggedIn === false" routerLink="/login">
    <img src="../image.jpg"/>
</a>

<a *ngIf="userIsLoggedIn() === true" routerLink="/dashboard">
    <img src="../image.jpg"/>
</a>

Other options: Do a (click)="yourFunction()" on the anchor of your logo. In yourFunction() you check if the user is logged in or not and them navigate them to the correct page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...