https://angular.io/api/router/RouterLink很好地概述了如何在Angular4中创建将用户带到不同路径的链接,但是我找不到如何以编程方式执行相同的操作而不需要用户单击链接
navigateByUrl
原文链接:https://www.f2er.com/angularjs/143687.html如下所用的routerLink指令:
<a [routerLink]="/inBox/33/messages/44">Open Message 44</a>
只是使用路由器及其navigateByUrl方法的命令式导航的包装:
router.navigateByUrl('/inBox/33/messages/44')
从资料来源可以看出:
export class RouterLink { ... @HostListener('click') onClick(): boolean { ... this.router.navigateByUrl(this.urlTree,extras); return true; }
因此,只要您需要将用户导航到另一个路由,只需注入路由器并使用navigateByUrl方法:
class MyComponent { constructor(router: Router) { this.router.navigateByUrl(...); } }
导航
router.navigate(['/inBox/33/messages/44'])
两者之间的差异
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'
,and calling
router.navigate('/inBox/33/messages/44')
will result in
'/inBox/33/messages/44(popup:compose)'
.
阅读更多the official docs.