简体   繁体   中英

How do I redirectTo child component with given parameter in angular2

app.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
        ]
    })

main.component

@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
    ]
})

im trying to achieve something like this:

when user enters a link with a number localhost:3000/2 it should redirect him to localhost:3000/2/Home

{ path: "/:userId", redirectTo: ["Main", {userId: 1}, "Home"] }

this redirects me to localhost:3000/1/Home is there a way to pass userI instead of specific value.

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" },
])

As it turns out i had to add useAsDefault: true on child route, so when the app.component redirects to "Main" it knows to which child it can redirect next. Also i changed { path: "/", redirectTo: ["Main", {userId:1}] }, for when userId is not present.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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