【问题标题】:How to routing to component with same url如何路由到具有相同 url 的组件
【发布时间】: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 和您的 HomeComponent ts 文件中注入您的 authService 并在您的 ngOnInit() 中放入一些逻辑,以隐藏 @987654328 @内容或您的SignInComponent
  • 我同意 axlj。每个组件都应该有一个单一的用途。因此,请考虑为您的主页定义一个组件,并为您的登录定义一个单独的组件。
  • @axlj 不,但如果有的话,我想找到解决方案。我看到一个 SPA 有这个,所以我想知道如何制作一个。

标签: angular typescript angular2-routing


【解决方案1】:

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

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

在你的 home-routing.module 中:

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

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

所以如果他没有连接,用户将不会加载你所有的应用程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-25
    • 2019-11-17
    • 2018-11-04
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2021-09-10
    相关资源
    最近更新 更多