How to use router.navigateByUrl and router.navigate in Angular

后端 未结 4 565
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 04:04

https://angular.io/api/router/RouterLink gives a good overview of how to create links that will take the user to a different route in Angular4, however I can\'t find how to

4条回答
  •  清歌不尽
    2020-12-08 04:39

    router.navigate vs router.navigateByUrl

    router.navigate is just a convenience method that wraps router.navigateByUrl, it boils down to:

    navigate(commands: any[], extras) {
        return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
    }
    

    As mentioned in other answers router.navigateByUrl will only accept absolute URLs:

    // This will work
    router.navigateByUrl("http://localhost/team/33/user/11")
    // This WON'T work even though relativeTo parameter is in the signature
    router.navigateByUrl("../22", {relativeTo: route})
    

    All the relative calculations are done by router.createUrlTree and router.navigate. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".." - go up, "path" - go down, {expand: true} - add query param, etc.. You can use it like this:

    // create /team/33/user/11
    router.navigate(['/team', 33, 'user', 11]);
    
    // assuming the current url is `/team/33/user/11` and the route points to `user/11`
    
    // navigate to /team/33/user/11/details
    router.navigate(['details'], {relativeTo: route});
    
    // navigate to /team/33/user/22
    router.navigate(['../22'], {relativeTo: route});
    
    // navigate to /team/44/user/22
    router.navigate(['../../team/44/user/22'], {relativeTo: route});
    

    That {relativeTo: route} parameter is important as that's what router will use as the root for relative operations.

    Get it through your component's constructor:

      // In my-awesome.component.ts:
    
      constructor(private route: ActivatedRoute, private router: Router) {}
      
      // Example call
      onNavigateClick() {
        // Navigates to a parent component
        this.router.navigate([..], { relativeTo: this.route })
      }
    

    routerLink directive

    Nicest thing about this directive is that it will retrieve the ActivatedRoute for you. Under the hood it's using already familiar:

    router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });
    

    Following variants will produce identical result:

    [routerLink]="['../..']"
    
    // if the string parameter is passed it will be wrapped into an array
    routerLink="../.."
    

提交回复
热议问题