如何使用angular2中的给定参数重定向到子组件

时间:2016-05-26 21:01:31

标签: angular angular2-routing

app.component

img.corner {
  margin-top: -20px;
  margin-left: -20px;
  margin-right: 20px;
  float: left;
  ...
}

main.component

@RouteConfig([   
        //{ path: "/:userId/...", component: MainComponent, name: "Main", useAsDefault: true },
        //{ path: "/:userId", redirectTo: ["Main", "Home"] },
        { path: "/:userId/...", component: MainComponent, name: "Main", useAsDefault: true },
        { path: "/:userId", redirectTo: ["Main", {userId: 1}, "Home"] },
    ])
    @Component({
        selector: "app-component",
        template: "<router-outlet></router-outlet>",
        directives: [
            ROUTER_DIRECTIVES
        ],
        providers: [
            RouteParams
        ]
    })

我试图实现这样的目标:

当用户输入编号为@RouteConfig([ { path: "/home/", component: HomeComponent, name: "Home" }, { path: "/products/:productId", component: ProductsComponent, name: "Products" }, { path: "/cv", component: CvComponent, name: "Cv" }, { path: "/contact", component: ContactComponent, name: "Contact" }, { path: "/home", redirectTo: ["Home"] }, ]) @Component({ selector: "main-component", templateUrl: "js/app/components/main.component/main.component.html", directives: [ ROUTER_DIRECTIVES, HeaderComponent, FooterComponent ] }) 的链接时,应将其重定向到localhost:3000/2

localhost:3000/2/Home

这会将我重定向到{ path: "/:userId", redirectTo: ["Main", {userId: 1}, "Home"] } 是否有办法传递userI而非特定值。

1 个答案:

答案 0 :(得分:1)

app.component

@RouteConfig([
        { path: "/:userId/...", component: MainComponent, name: "Main" },
        { path: "/", redirectTo: ["Main", {userId:1}] },

    ])

main.component

@RouteConfig([
    { path: "/home/", component: HomeComponent, name: "Home", useAsDefault: true},
    { path: "/products/:productId", component: ProductsComponent, name: "Products" },
    { path: "/cv", component: CvComponent, name: "Cv" },
    { path: "/contact", component: ContactComponent, name: "Contact" },
])

事实证明我必须在子路由上添加useAsDefault: true,所以当app.component重定向到“Main”时,它知道它可以重定向到哪个子节点。当userId不存在时,我也更改了{ path: "/", redirectTo: ["Main", {userId:1}] },