繁体   English   中英

Angular中router.navigateByUrl和router.navigate的使用方法

[英]How to use router.navigateByUrl and router.navigate in Angular

https://angular.io/api/router/RouterLink很好地概述了如何创建链接,将用户带到 Angular4 中的不同路线,但是我找不到如何以编程方式做同样的事情,而是需要用户点击链接

https://angular.io/api/router/RouterLink很好地概述了如何创建将用户带到Angular4中不同路径的链接,但是我找不到如何以编程方式执行相同的操作,而是需要用户单击链接

https://angular.io/api/router/RouterLink很好地概述了如何创建将用户带到Angular4中不同路径的链接,但是我找不到如何以编程方式执行相同的操作,而是需要用户单击链接

https://angular.io/api/router/RouterLink很好地概述了如何创建将用户带到Angular4中不同路径的链接,但是我找不到如何以编程方式执行相同的操作,而是需要用户单击链接

https://angular.io/api/router/RouterLink很好地概述了如何创建将用户带到Angular4中不同路径的链接,但是我找不到如何以编程方式执行相同的操作,而是需要用户单击链接

假设你在 http://localhost:4200 上运行你的服务器,你在 http://localhost:4200/abc 和路由模块下你定义了如下路径:

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

现在,我们将从@angular/router 如下导入 Router 并将其分配给构造函数中的任何变量(这里是 myRoute)。

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

现在在您的方法中,您将使用navigateByUrl重定向,这意味着如果您在http://localhost:4200/abc 上并尝试使用navigateByUrl 重定向到http://localhost:4200/abc/new,您将能够即它会首先尝试匹配 appRoutes 配置,一旦在子节点中找到,它将重定向到 LoadedComponent.Code 如下:

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

此外,如果我们使用导航,那么它将基于激活的路由工作,并且它与当前活动路由的变化很小:

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

在这里,如果我在 http://localhost:4200/abc 并且我有一个方法调用将它导航到新路由,那么它将根据当前活动路由触发,如果它有新的子路由,那么它将重定向到 http://localhost:4200/abc/new

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

我遇到了同样的问题。 我的解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM