如何在角度2中强制路由到空URL?

时间:2017-03-01 19:52:38

标签: angular angular-routing

我有component负责处理空url案例:

const loginRoutes: Routes = [
  { path: '',  component: LoginComponent }
];

成功登录后,用户将被路由到authenticated区域。

this.router.navigate(["/secured"]);

当用户点击Sign out时,在执行服务器端注销后,我尝试以下操作:

this.router.navigate([""])

这不会路由回LoginComponent,而是在3-5秒的延迟后重新加载整个应用程序。

我还有一个包含以下内容的应用程序级路由文件:

const appRoutes: Routes = [
  { path: '**',   redirectTo: '', pathMatch: 'full' }
];

1 个答案:

答案 0 :(得分:0)

我无法发表评论,所以我会将此作为答案。你能试试吗?

根据评论进行编辑: 由于登录组件在自己的模块中(我将其称为子模块)。试试这个:

只需添加{path: '', loadChildren: 'app/child/child.module#ChildModule'}

即可
const appRoutes: Routes = [
  { path: '**',   redirectTo: '', pathMatch: 'full' },
  { path: '', loadChildren: 'app/child/child.module#ChildModule'}
];

并在子模块中:

imports: [
    RouterModule.forChild([
        {
            path: '',
            component: LoginComponent
        }
    ])
]

理想情况下,你会这样做:

定义ChildRoutingModule:

import {NgModule}     from '@angular/core';
import {RouterModule} from '@angular/router';
@NgModule({
imports: [
    RouterModule.forChild([
        {
            path: '',
            component: LoginComponent
        }
    ])
],
exports: [
    RouterModule
]
})
export class ChildRoutingModule {}

在ChildModule中:

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {LoginComponent} from './login.component';
@NgModule({
imports: [
    CommonModule,
    ChildRoutingModule
],
declarations: [
    LoginComponent
]
})
export class ChildModule {}

在AppRoutingModule中:

import {NgModule}     from '@angular/core';
import {RouterModule} from '@angular/router';
@NgModule({
imports: [
    RouterModule.forRoot([
        {path: '**', redirectTo: '', pathMatch: 'full'},
        {path: '', loadChildren: 'app/child/child.module#ChildModule'}
    ])
],
exports: [
    RouterModule
]
})
export class AppRoutingModule {}

最后在应用程序模块中:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
import {AppRoutingModule} from './app-routing.module';

@NgModule({
imports: [
    BrowserModule,
    AppRoutingModule
],
declarations: [
    AppComponent
],
bootstrap: [AppComponent]
})
export class AppModule {}

希望这有帮助!