如何路由到具有相同url的组件
问题描述:
我有两个组件SignInComponent和HomeComponent。我希望HomeComponent是我的web应用程序的默认视图,但用户必须首先通过SignInComponent登录,并且这些组件具有与同一Url路由。问题是我不知道如何在它们之间导航,因为它们具有相同的Url。这里是我的应用程序,routing.module.ts文件:如何路由到具有相同url的组件
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 {}
这里是AuthGuard来检查线路接入HomeComponent,它将导航用户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: [...]
}
]
并配有后卫,你会重定向到登录,如果用户没有连接。
因此,如果用户没有连接,用户将不会加载所有应用程序。
这是一个很难的要求,他们必须是相同的网址?看起来你可能会让自己变得不必要的困难。 – axlj
我同意axlj。这种情况违背了路线的整个观点。如果他们必须在同一条路径上,我会把你的'SignInComponent'放入你的'HomeComponent'中,并放入你的'HomeComponent' ts文件中注入你的'authService',并在你的'ngOnInit()'中放入一些逻辑, 'HomeComponenet'内容或您的'SignInComponent' –
我同意axlj。每个组件应该有一个目的。因此,请考虑为您的主页定义一个组件,并为您的登录定义一个单独的组件。 – DeborahK