Angular 2(TypeScript) 处理与任何已定义路由路径不匹配的无效 URL

Angular 2(TypeScript) handle invalid urls that don't match with any defined routes' paths

在我的应用程序中,我有以下几行

@Component({
    selector: 'sampleSelector',
    template: `<router-outlet></router-outlet>`,
    directives: [ROUTER_DIRECTIVES],
    providers: [ROUTER_PROVIDERS, HTTP_PROVIDERS]
})
@RouteConfig([
    {
        path: '/...', name: 'Dashboard', component: DashboardCenterComponent, useAsDefault: true
    }
])
export class AppComponent {
}

当我连接到 /... 时,它显示 DashboardCenterComponent 并且没问题。但是问题是,当我重定向到任何其他页面时,我没有为其配置任何路由,它会显示空白屏幕。

子路由:

@RouteConfig([
    {path: '/', name: 'DashboardMain', component: DashboardComponent, useAsDefault: true}
])
export class DashboardCenterComponent {
}

我需要一种从不存在的路由重定向到根路由的机制。

例如,我访问了 localhost:3000/hello,但我没有相应的路线。 我需要重定向到 localhost:3000。 怎么做?

router.recognize可以救你

    import {Router} from 'angular2/router';
    import {Location} from 'angular2/platform/common';

    @Component({
        ....
    })
    @RouteConfig([
        ....
    ])
        export class AppComponent {
          constructor(router: Router, location: Location){

            router.subscribe(() => {

              router.recognize(location.path()).then((instruction) => {
                if(!instruction){
                  // this code will execute if there no route exists for the current url
                  router.navigate(['/DashboardMain']); 
                }
              });

           });

          }
        }

更新:添加了路由器订阅以在每次导航时检查url

在我的应用程序中,我有一个 ErrorComponent,当路由错误时我会显示它,但是您可以重定向到您想要的组件,例如:

{ path: '/*ErrorRoutes', name: 'NotFound', component: NotFoundComponent }

这意味着配置所有路由,但对于任何其他“/*”,请执行此操作

您的代码已更新:

 @Component({
        selector: 'sampleSelector',
        template: `<router-outlet></router-outlet>`,
        directives: [ROUTER_DIRECTIVES],
        providers: [ROUTER_PROVIDERS, HTTP_PROVIDERS]
    })
    @RouteConfig([
        {
            path: '/...', name: 'Dashboard', component: DashboardCenterComponent,    useAsDefault: true
        },
            { path: '/*NotFound', name: 'Dashboard', component: DashboardCenterComponent }
    ])
    export class AppComponent {
    }