https://angular.io/api/router/RouterLink很好地概述了如何创建将用户带到 Angular4 中不同路线的链接,但是我找不到如何以编程方式做同样的事情,而是需要用户单击链接
最佳答案
navigateByUrl
routerLink
指令像这样使用:
<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>
只是使用 router
及其 navigateByUrl 的命令式导航的包装器方法:
router.navigateByUrl('/inbox/33/messages/44')
从源码可以看出:
export class RouterLink {
...
@HostListener('click')
onClick(): boolean {
...
this.router.navigateByUrl(this.urlTree, extras);
return true;
}
因此,无论您需要将用户导航到另一条路线,只需注入(inject) router
并使用 navigateByUrl
方法:
class MyComponent {
constructor(router: Router) {
this.router.navigateByUrl(...);
}
}
导航
您可以使用路由器上的另一种方法 - navigate :
router.navigate(['/inbox/33/messages/44'])
两者的区别
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.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 withrouter.navigate(['/inbox/33/messages/44'])
will result in'/inbox/33/messages/44(popup:compose)'
.
阅读更多 the official docs .
关于angular - 如何在 Angular 中使用 router.navigateByUrl 和 router.navigate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45025334/