【问题标题】:Angular 2 setting app routing issueAngular 2设置应用程序路由问题
【发布时间】:2017-03-13 14:04:52
【问题描述】:

我是 Angular 2 的新手。我想在根 URL (http://localhost:4200) 上显示“HomeComponent”,在http://localhost:4200/posts 上显示“PostsComponent”。我在 app.routing.ts 设置了以下内容。

export const AppRoutes: Routes = [
  {
    path: '',
    component: AdminLayoutComponent,
    children: [{
      path: '',
      component: HomeComponent
    }, {
      path: 'posts',
      loadChildren: './posts/posts.module#PostsModule'
    },{
      path: '**',
      component: PageNotFoundComponent
    }]
  }
];

Home 组件第一次正确显示。当我访问帖子 URL(帖子组件也正确显示)并返回根 URL(通过单击链接 - 例如:主页链接)时,它显示“页面未找到组件”。但是当我重新加载页面时,它会正确显示主页组件。

我在这里错过了什么?

注意:如果我对“”(空)路径使用“redirectTo”选项,那么它正在工作。然后主页组件将显示在http://localhost:4200/home。但我想在 http://localhost:4200 显示 home 组件

【问题讨论】:

    标签: angular


    【解决方案1】:

    这是错误的网址

    path: '',
    component: AdminLayoutComponent,
    children: [{
      path: '',
      component: HomeComponent
    },
    

    根据您的配置,这是 HomeComponent 所需的路由:“//”

    尝试下一个方法

    export const AppRoutes: Routes = [
      {
        path: '',
        component: AdminLayoutComponent,
        children: [{
          path: 'home',
          component: HomeComponent
        }, {
          path: 'posts',
          loadChildren: './posts/posts.module#PostsModule'
        },{
          path: '**',
          component: PageNotFoundComponent
        }]
      }
    ];
    

    【讨论】:

    • 此配置在 localhost:4200/home 处显示主组件,并且为 root 显示“找不到页面”。但我想在根目录下显示 home 组件
    • 你导入了吗?从 './your path' 导入 { AdminLayoutComponent};
    【解决方案2】:

    当你登陆 Home 组件时,它会被重定向到空路径而不是 /home。所以尝试以下方法,它会有所帮助。它所做的是,只要找到空路径,它就会重定向到 Out home 组件。只需尝试添加我在下面写的行 >>> 添加的代码从这里开始

        export const AppRoutes: Routes = [
      {
        path: '',
        component: AdminLayoutComponent,
        children: [{
    
         // >>> ADDED CODE STARTS HERE
          path: '',
          redirectTo: 'home',
          pathMatch: 'full'
        }, 
        {
          path: 'home',
          Component: HomeComponent
        },
        // >>> ADDED CODE ENDS HERE
    
        {
          path: 'posts',
          loadChildren: './posts/posts.module#PostsModule'
        },{
          path: '**',
          component: PageNotFoundComponent
        }]
      }
    ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 2019-01-26
      • 2017-06-12
      相关资源
      最近更新 更多