How do I navigate to a parent route from a child route?

前端 未结 11 1988
Happy的楠姐
Happy的楠姐 2020-11-29 19:04

My problem is quite classic. I have a private part of an application which is behind a login form. When the login is successful, it goes to a child route for th

相关标签:
11条回答
  • 2020-11-29 19:13

    Another way could be like this

    this._router.navigateByUrl(this._router.url.substr(0, this._router.url.lastIndexOf('/'))); // go to parent URL
    

    and here is the constructor

    constructor(
        private _activatedRoute: ActivatedRoute,
        private _router: Router
      ) { }
    
    0 讨论(0)
  • 2020-11-29 19:15

    My routes have a pattern like this:

    • user/edit/1 -> Edit
    • user/create/0 -> Create
    • user/ -> List

    When i am on Edit page, for example, and i need go back to list page, i will return 2 levels up on the route.

    Thinking about that, i created my method with a "level" parameter.

    goBack(level: number = 1) {
        let commands = '../';
        this.router.navigate([commands.repeat(level)], { relativeTo: this.route });
    }
    

    So, to go from edit to list i call the method like that:

    this.goBack(2);
    
    0 讨论(0)
  • 2020-11-29 19:16

    without much ado:

    this.router.navigate(['..'], {relativeTo: this.activeRoute, skipLocationChange: true});
    

    parameter '..' makes navigation one level up, i.e. parent :)

    0 讨论(0)
  • 2020-11-29 19:29

    My solution is:

    const urlSplit = this._router.url.split('/');
    this._router.navigate([urlSplit.splice(0, urlSplit.length - 1).join('/')], { relativeTo: this._route.parent });
    

    And the Router injection:

    private readonly _router: Router
    
    0 讨论(0)
  • 2020-11-29 19:30

    This seems to work for me as of Spring 2017:

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

    Where your component ctor accepts ActivatedRoute and Router, imported as follows:

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

    0 讨论(0)
  • 2020-11-29 19:30

    To navigate to the parent component regardless of the number of parameters in the current route or the parent route: Angular 6 update 1/21/19

       let routerLink = this._aRoute.parent.snapshot.pathFromRoot
            .map((s) => s.url)
            .reduce((a, e) => {
                //Do NOT add last path!
                if (a.length + e.length !== this._aRoute.parent.snapshot.pathFromRoot.length) {
                    return a.concat(e);
                }
                return a;
            })
            .map((s) => s.path);
        this._router.navigate(routerLink);
    

    This has the added bonus of being an absolute route you can use with the singleton Router.

    (Angular 4+ for sure, probably Angular 2 too.)

    0 讨论(0)
提交回复
热议问题