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

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 do the same thing programmatically rather needing the user to click a link

184042 次浏览

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.

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.

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="../.."

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})

Let's say you're running your server on http://localhost:4200 and you're on http://localhost:4200/abc and under routing module you've defined path as below:

const appRoutes: Routes = [
{ path: 'abc', component: MainComponent, children: [
{path: '', component: InitialComponent},
{path: 'new', component: LoadedComponent}
]}]

Now, we'll import Router as below from @angular/router and assign it to any variable inside constructor(here myRoute).

import { Router } from '@angular/router';
constructor(private myRoute: Router) { }

Inside your method now you'll redirect using navigateByUrl which mean that if you're on http://localhost:4200/abc and trying to redirect using navigateByUrl to http://localhost:4200/abc/new you'll be able to i.e. it will first try to match the appRoutes config and once found in children it will redirect to LoadedComponent.Code is as below:

this.myRoute.navigateByUrl('abc/new');

Also, if we use navigate then it will work based on the activatedRoute and it has small change with current active route:

import { ActivatedRoute, Router } from '@angular/router';
constructor(private myRoute: Router, private activeRoute: ActivatedRoute) { }

Here, if I'm at http://localhost:4200/abc and I have a method call to navigate it to new route then it will be triggered based on the current active route and if it has new as Child Route then it will redirect to http://localhost:4200/abc/new

this.myRoute.navigate(['new'], {relativeTo: this.activeRoute});

I faced the same issue. My solution:

...
<p @click=parseHTML v-html=data.html></p>
...
methods: {
parseHTML(event) {
if (event.target.href) {
event.preventDefault();
if (event.target.href.includes(location.hostname)) {
this.$router.push(event.target.href)
}
}
}
}