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

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

    navigateByUrl

    routerLink directive as used like this:

    Open Message 44
    

    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.

提交回复
热议问题