Angular2 Router Navigation

angular typescript web routing

316 观看

2回复

64 作者的声誉

I'm trying to test out router navigation in my application, however each time I attempt to navigate to my url I get thrown back to the homepage.

The router should navigate to the next page when the user selects a row to complete a form, like this:

  onUserRowSelect(event): void {
    this.router.navigate(['myform']);}

However, myforms is not being navigated to, heres how I defined the routes:

    const routes: Routes = [
  {
    path: '',
    component: UserAdminComponent,
    children: [
      {
        path: 'createuser',
        component: CreateUserComponent
      },
      {
        path: 'updateuser',
        component: UpdateUserComponent,
        children: [
          {
            path: 'myform',
            component: UpdateFormComponent,
          }
        ]
      },
    ]
  },

];

So the navigate to myURL/useradmin/updateuser/myform does not work at all (if the child routes are working even).

I can elaborate more if needed. Thank you

作者: MostafaItani 的来源 发布者: 2017 年 12 月 27 日

回应 2


0

142702 作者的声誉

You should provide the complete path starting from the parent

   this.router.navigate(['useradmin','updateuser','myform']);}
作者: Sajeetharan 发布者: 2017 年 12 月 27 日

1

38776 作者的声誉

决定

If you want to navigate to a child route of the current route (e.g. from updateuser to updateuser/myform), you can use relative navigation:

import { Router, ActivatedRoute } from '@angular/router';

constructor(
    private route: ActivatedRoute,
    private router: Router) { 
}

onUserRowSelect(event): void {
    this.router.navigate(['./myform'], { relativeTo: this.route });
}

You can find many more navigation cases in this detailed answer by TetraDev.


Update: if the UpdateFormComponent is to replace the UpdateUserComponent when navigating, then they should both be direct children of UserAdminComponent:

  const routes: Routes = [
  {
    path: '',
    component: UserAdminComponent,
    children: [
      {
        path: 'createuser',
        component: CreateUserComponent
      },
      {
        path: 'updateuser',
        component: UpdateUserComponent
      },
      {
        path: 'myform',
        component: UpdateFormComponent
      }
    ]
  }];

and the navigation would be perform this way:

onUserRowSelect(event): void {
    this.router.navigate(['../myform'], { relativeTo: this.route });
}
作者: ConnorsFan 发布者: 2017 年 12 月 28 日
32x32