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

后端 未结 4 543
伪装坚强ぢ
伪装坚强ぢ 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:36

    From my understanding, router.navigate is used to navigate relatively to current path. For eg : If our current path is abc.com/user, we want to navigate to the url : abc.com/user/10 for this scenario we can use router.navigate .


    router.navigateByUrl() is used for absolute path navigation.

    ie,

    If we need to navigate to entirely different route in that case we can use router.navigateByUrl

    For example if we need to navigate from abc.com/user to abc.com/assets, in this case we can use router.navigateByUrl()


    Syntax :

    router.navigateByUrl(' ---- String ----');

    router.navigate([], {relativeTo: route})

    0 讨论(0)
  • 2020-12-08 04:37

    navigateByUrl

    routerLink directive as used like this:

    <a [routerLink]="/inbox/33/messages/44">Open Message 44</a>
    

    is just a wrapper around imperative navigation using router and its navigateByUrl method:

    router.navigateByUrl('/inbox/33/messages/44')
    

    as can be seen from the sources:

    export class RouterLink {
      ...
    
      @HostListener('click')
      onClick(): boolean {
        ...
        this.router.navigateByUrl(this.urlTree, extras);
        return true;
      }
    

    So wherever you need to navigate a user to another route, just inject the router and use navigateByUrl method:

    class MyComponent {
       constructor(router: Router) {
          this.router.navigateByUrl(...);
       }
    }
    

    navigate

    There's another method on the router that you can use - navigate:

    router.navigate(['/inbox/33/messages/44'])
    

    difference between the two

    Using router.navigateByUrl is similar to changing the location bar directly–we are providing the “whole” new URL. Whereas router.navigate creates a new URL by applying an array of passed-in commands, a patch, to the current URL.

    To see the difference clearly, imagine that the current URL is '/inbox/11/messages/22(popup:compose)'.

    With this URL, calling router.navigateByUrl('/inbox/33/messages/44') will result in '/inbox/33/messages/44'. But calling it with router.navigate(['/inbox/33/messages/44']) will result in '/inbox/33/messages/44(popup:compose)'.

    Read more in the official docs.

    0 讨论(0)
  • 2020-12-08 04:38

    In addition to the provided answer, there are more details to navigate. From the function's comments:

    /**
     * Navigate based on the provided array of commands and a starting point.
     * If no starting route is provided, the navigation is absolute.
     *
     * Returns a promise that:
     * - resolves to 'true' when navigation succeeds,
     * - resolves to 'false' when navigation fails,
     * - is rejected when an error happens.
     *
     * ### Usage
     *
     * ```
     * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
     *
     * // Navigate without updating the URL
     * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
     * ```
     *
     * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
     * URL.
     */
    

    The Router Guide has more details on programmatic navigation.

    0 讨论(0)
  • 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="../.."
    
    0 讨论(0)
提交回复
热议问题