【发布时间】:2017-10-06 21:26:58
【问题描述】:
我有两个组件 SignInComponent 和 HomeComponent。我希望 HomeComponent 是我的 Web 应用程序的默认视图,但用户必须先通过 SignInComponent 登录,并且这些组件的路由具有相同的 Url。问题是我不知道如何在它们之间导航,因为它们具有相同的 Url。这是我的 app-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 {}
这里是 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;
}
}
【问题讨论】:
-
它们必须是相同的 URL 是硬性要求吗?看来您可能会给自己造成不必要的困难。
-
我同意 axlj。这种方式违背了拥有路线的全部意义。如果他们必须在同一条路线上,我会将您的
SignInComponent放入您的HomeComponent和您的HomeComponentts 文件中注入您的authService并在您的ngOnInit()中放入一些逻辑,以隐藏 @987654328 @内容或您的SignInComponent -
我同意 axlj。每个组件都应该有一个单一的用途。因此,请考虑为您的主页定义一个组件,并为您的登录定义一个单独的组件。
-
@axlj 不,但如果有的话,我想找到解决方案。我看到一个 SPA 有这个,所以我想知道如何制作一个。
标签: angular typescript angular2-routing