如何路由到具有相同 url 的组件

How to routing to component with same url

我有两个组件 SignInComponent 和 HomeComponent。我希望 HomeComponent 是我的 Web 应用程序的默认视图,但用户必须先通过 SignInComponent 登录,并且这些组件具有相同的路由 Url。问题是我不知道如何在它们之间导航,因为它们具有相同的 Url。这是我的应用程序-routing.module.ts 文件:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { SignInComponent } from '../components/sign-in/sign-in.component';
import { HomeComponent } from '../components/home/home.component';

const appRoutes: Routes = [
    { path: '', component: HomeComponent, canActivate: [AuthGuard]},
    { path: '', component: SignInComponent}
];

@NgModule({
    imports: [
        RouterModule.forRoot(
            appRoutes,
            { enableTracing: false }
        )
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutingModule {}

这里是用于检查对 HomeComponent 的路由访问的 AuthGuard,如果用户未登录,它将导航到 SignInComponent:

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';

import { AuthenticationService } from '../services/authentication.service';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router, private authService: AuthenticationService) { }

    canActivate() {
        if (this.authService.checkCredentials()) {
            return true;
        }
        this.router.navigate(['']); // The problem is here
        return false;
    }
}

最简单的方法是为您的登录创建一个路由。

const routes : Routes = [
    {
        path: '',
        loadChildren: 'app/pages/pages.module#HomeModule'
    }, {
        path: 'login',
        component: LoginComponent
    },{
        path: '404',
        component: Page404Component
    }, {
        path: '**',
        redirectTo: '/404'
    }
];

在你家-routing.module:

const routes: Routes = [
   {
       path: '',
       canActivate: [AuthGuard],
       component: HomeComponent,
       children: [...]
   }
]

并且使用 guard,如果用户未连接,您将重定向到登录。

因此,如果用户未连接,他将不会加载您的所有应用程序。