如何在Angular中使用router.navigateByUrl和router.navigate [英] How to use router.navigateByUrl and router.navigate in Angular

查看:1190
本文介绍了如何在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. Whereas router.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)'.

了解更多官方文档

这篇关于如何在Angular中使用router.navigateByUrl和router.navigate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆