简体   繁体   English

Angular2 路由器(@angular/router),如何设置默认路由?

[英]Angular2 router (@angular/router), how to set default route?

How can I set a default route in my @Routes route metadata collection?如何在我的 @Routes 路由元数据集合中设置默认路由? If you use the angular2 router from @angular/router-deprecated you define the routes in @routeConfig object, which is a collection of route objects, but these route objects have more attributes on them.如果您使用来自@angular/router-deprecated 的 angular2 路由器,您可以在 @routeConfig 对象中定义路由,该对象是路由对象的集合,但这些路由对象具有更多属性。 For instance they have 'name' and 'useAsDefualt' attributes whereas the routes defined out of @angular/router do not.例如,它们具有 'name' 和 'useAsDefualt' 属性,而由 @angular/router 定义的路由则没有。 I would like to write my new app using the new router, but how do i use the new router and set a default route?我想使用新路由器编写我的新应用程序,但如何使用新路由器并设置默认路由?

This is my main app component which defines my routes:这是我的主要应用组件,它定义了我的路线:

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 { }

The route definitions seem to be working fine, when I click on anchor tags like this one:当我点击这样的锚标签时,路线定义似乎工作正常:

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

It transitions to the associated route.它转换到关联的路由。 My only issue is that when my app loads it doesn't have a route active.我唯一的问题是,当我的应用程序加载时,它没有激活的路由。 How do i define a default route that is active when my app bootstraps?我如何定义在我的应用程序引导时处于活动状态的默认路由?

Thanks!谢谢!

V2.0.0 and later V2.0.0 及更高版本

See also see https://angular.io/guide/router#the-default-route-to-heroes另见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 }
    ] 
  }
];

There is also the catch-all route还有包罗万象的路线

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

which redirects "invalid" urls.重定向“无效”网址。

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

Use path / and redirectTo使用路径/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.1 @angular/路由器

The RC router doesn't yet support useAsDefault . RC 路由器尚不支持useAsDefault As a workaround you can navigate explicitely.作为一种解决方法,您可以明确导航。

In the root component在根组件中

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

for other components对于其他组件

export class OtherComponent {
  constructor(private router:Router) {}

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

You set path of route is ''.您设置的路线路径是''。 Example for DashboardComponent is load first. DashboardComponent 的示例首先加载。

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

Hope it help you.希望对你有帮助。

In Angular 2+, you can set route to default page by adding this route to your route module.在 Angular 2+ 中,您可以通过将此路由添加到路由模块来将路由设置为默认页面。 In this case login is my target route for the default page.在这种情况下,登录是我默认页面的目标路由。

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

I faced same issue apply all possible solution but finally this solve my problem我遇到了同样的问题,应用了所有可能的解决方案,但最终这解决了我的问题

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

Hope this will help you.希望这会帮助你。

Suppose you want to load RegistrationComponent on load and then ConfirmationComponent on some event click on RegistrationComponent .假设您想在加载时加载RegistrationComponent ,然后在某些事件上单击ConfirmationComponent ,然后单击RegistrationComponent

So in appModule.ts , you can write like this.所以在appModule.ts ,你可以这样写。

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

OR

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

is also fine.也不错。 Choose whatever you like.选择任何你喜欢的。

according to documentation you should just根据文档,你应该只是

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

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

With the current version of angular 2 you can't use '/' on a path or give a name to your route.使用当前版本的 angular 2,您不能在路径上使用“/”或为您的路线命名。 What you can do is create a route file like "app.routes.ts" and import your components, make sure of the path when importing.您可以做的是创建一个类似于“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';`

Add:添加:

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

Then your routes:然后你的路线:

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

Then export:然后导出:

export  const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)]

In your main.ts import APP_ROUTER_PROVIDERS and add bootstrap the router providers to the main.ts like this:在您的 main.ts 中导入APP_ROUTER_PROVIDERS并将路由器提供程序的引导程序添加到 main.ts 中,如下所示:

bootstrap(AppComponent,[APP_ROUTER_PROVIDERS]);

Finally, your link will look like this:最后,您的链接将如下所示:

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

Only you need to add other parameter in your route, the parameter is useAsDefault:true.只需要在路由中添加其他参数,该参数为useAsDefault:true。 For example, if you want the DashboardComponent as default you need to do this:例如,如果您希望 DashboardComponent 作为默认值,则需要执行以下操作:

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

I recomend you to add names to your routes.我建议您为路线添加名称。

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

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

{ path: '', component: DashboardComponent },

I just faced the same issue, I managed to make it work on my machine, however the change I did is not the same way it is mentioned in the documentation so it could be an issue of angular version routing module, mine is Angular 7我刚刚遇到了同样的问题,我设法让它在我的机器上运行,但是我所做的更改与文档中提到的方式不同,因此它可能是 Angular 版本路由模块的问题,我的是 Angular 7

It only worked when I changed the lazy module main route entry path with same path as configured at the app-routes.ts它仅在我更改了与 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},
                ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM