【问题标题】:Angular2 router (@angular/router), how to set default route?Angular2 路由器(@angular/router),如何设置默认路由?
【发布时间】:2016-10-02 23:21:55
【问题描述】:

如何在我的@Routes 路由元数据集合中设置默认路由?如果您使用 @angular/router-deprecated 中的 angular2 路由器,您将在 @routeConfig 对象中定义路由,该对象是路由对象的集合,但这些路由对象具有更多属性。例如,它们具有 'name' 和 'useAsDefualt' 属性,而在 @angular/router 之外定义的路由则没有。我想使用新路由器编写我的新应用程序,但是如何使用新路由器并设置默认路由?

这是我的主要应用程序组件,它定义了我的路线:

import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ConfigManagerComponent } from './configManager/configManager.component';
import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
import { MergeComponent } from './merge/merge.component';

import { ROUTER_DIRECTIVES, Routes } from '@angular/router';


@Component({
    selector: 'app-container',
    templateUrl: 'app/app.component.html',
    directives: [ROUTER_DIRECTIVES]
})

@Routes([

        { path: '/Dashboard', component: DashboardComponent },
        { path: '/ConfigManager', component: ConfigManagerComponent },
        { path: '/Merge', component: MergeComponent },
        { path: '/ApplicationManagement', component: ApplicationMgmtComponent }
])

export class AppComponent { }

当我点击像这样的锚标签时,路由定义似乎工作正常:

<li class="nav hidden-xs"><a [routerLink]="['./Dashboard']">Dashboard</a>/li>

它转换到关联的路由。我唯一的问题是,当我的应用加载时,它没有激活的路由。如何定义在我的应用启动时处于活动状态的默认路由?

谢谢!

【问题讨论】:

    标签: angular


    【解决方案1】:

    你设置的路径路径是''。 DashboardComponent 的示例是先加载。

    @Routes([
            { path: '', component: DashboardComponent },
            { path: '/ConfigManager', component: ConfigManagerComponent },
            { path: '/Merge', component: MergeComponent },
            { path: '/ApplicationManagement', component: ApplicationMgmtComponent }
    ])
    

    希望对你有帮助。

    【讨论】:

    • 请注意,在加载时,应用程序将导航到 DashboardComponent,但 URL 将为空而不是 /dashboard
    • 感谢您提供这种方法。我唯一犹豫的是路由没有在 url 中明确引用。我想维护 url 上的 /Dashboard 后缀。但否则这会非常有效。
    【解决方案2】:

    V2.0.0 及更高版本

    另见https://angular.io/guide/router#the-default-route-to-heroes

    RouterConfig = [
      { path: '', redirectTo: '/heroes', pathMatch: 'full' },
      { path: 'heroes', component: HeroComponent,
        children: [
          { path: '', redirectTo: '/detail', pathMatch: 'full' },
          { path: 'detail', component: HeroDetailComponent }
        ] 
      }
    ];
    

    还有包罗万象的路线

    { path: '**', redirectTo: '/heroes', pathMatch: 'full' },
    

    重定向“无效”网址。

    V3-alpha(符拉迪沃斯托克)

    使用路径/redirectTo

    RouterConfig = [
      { path: '/', redirectTo: 'heroes', terminal: true },
      { path: 'heroes', component: HeroComponent,
        children: [
          { path: '/', redirectTo: 'detail', terminal: true },
          { path: 'detail', component: HeroDetailComponent }
        ] 
      }
    ];
    

    RC.1 @angular/router

    RC 路由器还不支持useAsDefault。作为一种解决方法,您可以显式导航。

    在根组件中

    export class AppComponent {
      constructor(router:Router) {
        router.navigate(['/Merge']);
      }
    }
    

    对于其他组件

    export class OtherComponent {
      constructor(private router:Router) {}
    
      routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) : void {
        this.router.navigate(['SomeRoute'], curr);
      }
    }
    

    【讨论】:

    • 当我尝试在构造函数中使用 Rotuer 时,Typescript 抱怨找不到“路由器”。我需要导入这个吗?
    • 您需要导入文件中使用的任何类型。如果您将Router 作为类型添加到任何变量或参数,则需要导入它。
    • 是的,在我发布后我尝试了这个: import { ROUTER_DIRECTIVES, Routes, Router } from '@angular/router';现在似乎可以工作了,谢谢!
    • 您在这一行缺少一个右大括号:{ path: '', redirectTo: '/heroes', pathMatch: 'full',我无法添加它,因为编辑必须至少有 6 个字符,请添加
    • @GünterZöchbauer 这是我这边的一个错误。当有一个哈希片段并且调用window.location.hash = '' 之前的导航时,它根本不会导航(DefaultStrategy)。
    【解决方案3】:

    使用当前版本的 Angular 2,您不能在路径上使用“/”或为您的路线命名。 您可以做的是创建一个类似“app.routes.ts”的路由文件并导入您的组件,在导入时确保路径。

    import { Component } from '@angular/core';
    import { DashboardComponent } from './dashboard/dashboard.component';
    import { ConfigManagerComponent } from './configManager/configManager.component';
    import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
    import { MergeComponent } from './merge/merge.component';`
    

    添加:

    import {RouterConfig, provideRouter } from '@angular/router';
    

    然后你的路线:

    const routes:RouterConfig = [      
        { path: 'Dashboard', component: DashboardComponent },
        { path: 'ConfigManager', component: ConfigManagerComponent },
        { path: 'Merge', component: MergeComponent },
        { path: 'ApplicationManagement', component: ApplicationMgmtComponent }
     ];
    

    然后导出:

    export  const APP_ROUTER_PROVIDERS = [
        provideRouter(routes)]
    

    在您的 main.ts 中导入 APP_ROUTER_PROVIDERS 并将引导路由器提供程序添加到 main.ts,如下所示:

    bootstrap(AppComponent,[APP_ROUTER_PROVIDERS]);
    

    最后,您的链接将如下所示:

    li class="nav hidden-xs"><a [routerLink]="['./Dashboard']" routerLinkActive="active">Dashboard</a>/li>
    

    【讨论】:

      【解决方案4】:

      只需要在路由中添加其他参数,参数为useAsDefault:true。例如,如果您希望 DashboardComponent 作为默认值,您需要这样做:

      @RouteConfig([
          { path: '/Dashboard', component: DashboardComponent , useAsDefault:true},
          .
          .
          .
          ])
      

      我建议您为路线添加名称。

      { path: '/Dashboard',name:'Dashboard', component: DashboardComponent , useAsDefault:true}
      

      【讨论】:

        【解决方案5】:

        路径应留空以使其成为默认组件。

        { path: '', component: DashboardComponent },
        

        【讨论】:

          【解决方案6】:

          在 Angular 2+ 中,您可以通过将此路由添加到您的路由模块来将路由设置为默认页面。在这种情况下,登录是我默认页面的目标路由。

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

          【讨论】:

            【解决方案7】:

            我遇到同样的问题应用所有可能的解决方案,但最终这解决了我的问题

            export class AppRoutingModule {
            constructor(private router: Router) {
                this.router.errorHandler = (error: any) => {
                    this.router.navigate(['404']); // or redirect to default route
                }
              }
            }
            

            希望这会对你有所帮助。

            【讨论】:

              【解决方案8】:

              假设您想在加载时加载 RegistrationComponent,然后在单击 RegistrationComponent 的某个事件上加载 ConfirmationComponent

              所以在appModule.ts,你可以这样写。

              RouterModule.forRoot([
                    { 
                      path: '', 
                      redirectTo: 'registration', 
                      pathMatch: 'full'
                     },
                     { 
                      path: 'registration', 
                      component: RegistrationComponent
                     },
                    {
                      path : 'confirmation',
                      component: ConfirmationComponent
                    }
                  ]) 
              

              RouterModule.forRoot([
                     { 
                      path: '', 
                      component: RegistrationComponent
                     },
                    {
                      path : 'confirmation',
                      component: ConfirmationComponent
                    }
                  ]) 
              

              也不错。 选择你喜欢的。

              【讨论】:

                【解决方案9】:

                根据文档,你应该只是

                { path: '**', component: DefaultLayoutComponent }
                

                在您的 app-routing.module.ts 上 来源:https://angular.io/guide/router

                【讨论】:

                • 速记,设置路径的顺序很重要。
                【解决方案10】:

                我刚刚遇到了同样的问题,我设法让它在我的机器上运行,但是我所做的更改与文档中提到的方式不同,因此它可能是角度版本路由模块的问题,我的是角 7

                仅当我使用与 app-routes.ts 中配置的相同路径更改惰性模块主路由条目路径时才有效

                routes = [{path:'', redirectTo: '\home\default', pathMatch: 'full'},
                           {path: '', 
                           children: [{
                             path:'home',
                             loadChildren :'lazy module path'      
                           }]
                
                         }];
                
                 routes configured at HomeModule
                 const routes = [{path: 'home', redirectTo: 'default', pathMatch: 'full'},
                             {path: 'default', component: MyPageComponent},
                            ]
                
                 instead of 
                 const routes = [{path: '', redirectTo: 'default', pathMatch: 'full'},
                                   {path: 'default', component: MyPageComponent},
                                ]
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-11-21
                  • 2016-01-14
                  • 1970-01-01
                  • 2016-08-21
                  • 2018-01-14
                  相关资源
                  最近更新 更多