简体   繁体   中英

What is the difference between router.navigate and router.parent.navigate in Angular2?

Actually I want to know the difference between router.navigate(['User']) and router.parent.navigate(['User']) . In my Angular2 project act same things for both.

thanks advance

You try to navigate to the route defined in the current router ( router.navigate(['User']) or to a one defined in the parent router ( router.parent.navigate(['User']) ).

As a matter of fact, you can define several levels of routes. If the User route is defined in the route config associated with the router, router.navigate(['User']) will work. If it's in the route config associated with the parent router, router.parent.navigate(['User']) will work.

For example, if you have two levels and want to navigate to the root level, you can use this:

router.navigate(['/User']);

Example

  • In the AppComponent component (application component):

     @RouteConfig([ { path: '/sub/...', name: 'SubComponent', component: SubComponent, useAsDefault: true }, {path: '/user', name: 'User', component: UserComponent} {path: '/other', name: 'Other', component: OtherComponent} ])
  • In the SubComponent component:

     @RouteConfig([ {path: '/test', name: 'Test', component: TestComponent} ])

In this case, router.parent.navigate(['User']) will work for components defined in routes of the SubComponent component (for example: TestComponent ). router.navigate(['User']) will work for components defined in routes of the AppComponent component (for example: OtherComponent ).

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