Angular 2路由重定向到子路由

标签 angular routing children

我是 Angular 2 的新手。我想为我的应用程序的每个部分创建独立的模块。例如,我使用默认组件创建了 AuthModule - AuthComponent,其中包含用于其子组件(SignIn 或 SignUp)的 router-outlet。所以我想实现以下场景:

  1. 当导航到/- root off app - 重定向到/auth
  2. 重定向到/auth 后 - 使用路由器导出加载 AuthComponent
  3. 加载 AppComponent 后 - 通过重定向到/auth/sign-in 加载默认登录组件

但是当我转到 localhost/时,我得到了我想要的重定向到/auth,但是下一个登录重定向没有出现。

我的代码: app.routing

const routes: Routes = [
  {
      path: '', 
      redirectTo: '/auth', 
      pathMatch: 'full'
  }
];

export const appRouting: ModuleWithProviders = RouterModule.forRoot(routes);

auth.routing

const routes: Routes = [
  {
    path: 'auth',
    component: AuthComponent,
    children: [
      {
         path: '', 
         redirectTo: 'sign-in', 
         pathMatch: 'full'
      },
      {
         path: 'sign-in', 
         component: SignInComponent
      }
    ]
  },

];

export const authRouting: ModuleWithProviders = RouterModule.forChild(routes);

auth.component.html

<div class="container">
    <h1>Auth component</h1>
    <router-outlet></router-outlet>
</div>

结果:

code

result

Environment @angular/cli: 1.0.0-rc.2 node: 7.7.1 os: win32 x64

最佳答案

我也遇到了同样的问题。这似乎是一个 Angular 技巧: 如果您删除“redirectTo”字段中的前导斜线,您的应用程序将成功重定向到 auth/sign-in。

在 app.routing 中使用它:

const routes: Routes = [ 

    {path: '', redirectTo: 'auth', pathMatch: 'full'}, 

];

“redirectTo”值以“/”= 绝对路径开头

‘redirectTo’ 值以没有‘/’ = 相对路径的方式开始

阅读更多相关信息:https://vsavkin.com/angular-router-understanding-redirects-2826177761fc

P.S 我认为你的结构比 YounesM 的结构更正确。父模块不能保留子路由:“app”模块不知道“auth”模块有子模块“sign-in”。

关于Angular 2路由重定向到子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42874859/

相关文章:

node.js - Windows 10 中的 npm 安装错误 ( npm install -g angular-cli )

Angular 2路由重定向不起作用

angular - 如何使自定义表单组件与 Angular2 中的表单验证集成?

c# - ASP.NET MVC 2 中具有一个名称的多个 Controller

angular - mat-card-avatar 在初始页面加载时无法正确呈现

sharepoint - 为什么 PreApplicationStartMethodAttribute() 在 SharePoint 2013 中不起作用?

php - Silex 路由 .htaccess webroot

javascript - 如何使用 JavaScript 动态创建 HTML 标签(带有内容)?

Android:在单独的线程中将许多子项添加到布局

reactjs - 对 child 使用 “React.ReactNode”类型时出错。我应该使用哪种类型?