如何在Angular中使用router.navigateByUrl和router.navigate
https://angular.io/api/router/RouterLink 很好地概述了如何创建将用户带到Angular4中不同路线的链接,但是我找不到如何以编程方式执行相同的操作,而是需要用户单击链接
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
navigateByUrl
routerLink
指令如下使用:
<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>
只是使用 router
的命令式导航的包装>及其 navigateByUrl 方法:
router.navigateByUrl('/inbox/33/messages/44')
$ b从来源中可以看到$ b
as can be seen from the sources:
export class RouterLink {
...
@HostListener('click')
onClick(): boolean {
...
this.router.navigateByUrl(this.urlTree, extras);
return true;
}
因此,只要您需要将用户导航到其他路线,只需注入路由器并使用 navigateByUrl
方法:
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(...);
}
}
导航
您可以在路由器上使用另一种方法-导航:
router.navigate(['/inbox/33/messages/44'])
两者之差
difference between the two
使用
router.navigateByUrl
类似于直接更改位置栏
-我们提供了整个新URL。而router.navigate
通过将传入的
命令(一个补丁)数组应用于当前URL来创建新的URL。
Using
router.navigateByUrl
is similar to changing the location bar directly–we are providing the "whole" new URL. Whereasrouter.navigate
creates a new URL by applying an array of passed-in commands, a patch, to the current URL.
要清楚地看到它们之间的区别,请假设当前URL是'/ inbox / 11 / messages / 22(popup:compose)'
。
To see the difference clearly, imagine that the current URL is
'/inbox/11/messages/22(popup:compose)'
.
使用此URL,调用 router.navigateByUrl('/ inbox / 33 / messages / 44')
会导致'/ inbox / 33 / messages / 44'
。但是用 router.navigate(['/ inbox / 33 / messages / 44'])
调用它会导致'/ inbox / 33 / messages / 44(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)'
.
了解更多官方文档。