angular – 路由重定向到root

我正在尝试使用Router.navigate方法进行路由.我按照说明书写了这封信,但是当我通过API路由时,它重新加载了根页面.

在我的RootComponent中我试图使用

this._router.navigate([‘ABC’, ‘Page1’]); which should redirect me to application/abc/xyz

但是,如果我通过浏览器直接访问application / abc / xyz,它将无缝运行

app.component.ts

import {Component} from "angular2/core";
import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from "angular2/router";
import {RootComponent} from "./components/root.component";
import {Page1Component} from "./components/page1.component";


@Component({
    selector: 'app',
    template: '<router-outlet></router-outlet>',
    directives: [ROUTER_DIRECTIVES],
    providers: [
        ROUTER_PROVIDERS
    ]
})

@RouteConfig([
    {
        path: '',
        name: 'Root',
        component: RootComponent,
        useAsDefault: true
    },
    {
        path: '/abc/...',
        name: 'ABC',
        component: ABCComponent
    }
])

export class AppComponent {
}

ABCComponent

@Component({
    selector: 'abc',
    template: '<router-outlet></router-outlet>',
    directives: [ROUTER_DIRECTIVES]
})

@RouteConfig([
    {
        path: '/xyz',
        name: 'Page1',
        component: Page1Component
    }
])
export class ABCComponent{

    constructor(private _router:Router){
    }

}

Page1Component

import {Component} from "angular2/core";
import {Router} from "angular2/router";

@Component({
    selector: 'page1',
    template: '<h1>Page1</h1>'
})

export class Page1Component{

    constructor(private _router:Router){
    }
}

我究竟做错了什么?

编辑

解释它甚至更简单的术语

                              Application (2 routes at root level)
                                  |                        |
           Default ("/") - Root Component              /abc/ ABC Component
                                                           |
                                                       /abc/xyz Page1 Component

我想要做的是,从Root Component导航到Page1.

从S.alem plunkr逆向工程后,这是解决方案

http://plnkr.co/edit/F1p6aQNJ7lREHCiVnKEP?p=preview

最佳答案 尝试使用主路由器(AppComponent的路由器).你可以用这样的方法得到它:

getMainRouter(router?: Router):Router {
  if (router.parent === null) {
    return router;
  }
  return this.getMainRouter(router.parent);
}

所以你的RootComponent可以是这样的:

// imports...

@Component({
    selector: 'root',
    template: '<h1>Root Component</h1>'
})

export class RootComponent{

    private _mainRouter: Router;

    constructor(private _router:Router){
        this._mainRouter = this.getMainRouter(this._router);
    }

    routeToSomewhere():void {
        this._mainRouter.navigate(['./ABC', 'Page1']);
    }

    private getMainRouter(router?: Router):Router {
        if (router.parent === null) {
            return router;
        }
        return this.getMainRouter(router.parent);
    }
}

这是一个plunker显示.我分叉了Hero Tutorial,但是如果你休闲AppComponent的路由配置,你可以看到相关的代码.在单独的窗口上启动plunker以查看浏览器URL.

点赞