【发布时间】:2018-12-03 01:56:30
【问题描述】:
我的 Angular 6 应用程序中有两个模块,一个是应用程序模块,另一个是用户模块,我正在尝试实现用户模块的延迟加载。如果我手动点击 URL,则路由有效,然后显示来自用户模块的正确页面。但是当我尝试从标题组件导航时,它并没有导航到用户页面,而是转到了默认页面。
Header.html
<form class="form-inline my-2 my-lg-0">
<button class="btn btn-secondary my-2 my-sm-0" type="submit" routerLink="/user/login">Login</button>
<button class="btn btn-secondary my-2 my-sm-0" type="submit" routerLink="/user/register">Register</button>
</form>
应用路由模块
import { NgModule, Component } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { WelcomeComponent } from './components/welcome/welcome.component';
import { PagenotfoundComponent } from './components/pagenotfound/pagenotfound.component';
const routes: Routes = [
{
path:'welcome',
component:WelcomeComponent
},
{
path:'user',
loadChildren:'./user/user.module#UserModule'
},
{
path: '',
redirectTo: 'welcome',
pathMatch: 'full' },
{
path: '**',
component: PagenotfoundComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
用户路由模块
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './components/login/login.component';
import { RegisterComponent } from './components/register/register.component';
const routes: Routes = [
{
path:'login',
component: LoginComponent
},
{
path:'register',
component:RegisterComponent
},
{
path:'',
redirectTo:'login',
pathMatch:'full'
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class UserRoutingModule { }
应用模块
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component';
import { WelcomeComponent } from './components/welcome/welcome.component';
import { PagenotfoundComponent } from './components/pagenotfound/pagenotfound.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
WelcomeComponent,
PagenotfoundComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
所以当我点击登录按钮时,我可以看到登录页面,但它立即重定向到欢迎页面 (http://localhost:4200/welcome)
【问题讨论】:
-
你能分享你的app.module吗
-
上面更新了应用模块。谢谢。
-
您可以尝试将 ``` path: '', redirectTo: 'welcome'``` 更改为 path: '', redirectTo: 'login'.. 不确定这是不是您想要的。 .
-
不更改登录将不起作用。因为 loginComponent 是另一个模块的一部分
-
@DeepuNair 你能创建一个 stackblitz 例子来重现这个问题吗?