简体   繁体   English

如何将绝对链接视为Angular中的相对路线?

[英]How to treat absolute links as relative routes in Angular?

I have an inbox component that shows the user messages which are generated as HTML on the backend. 我有一个收件箱组件,用于显示在后端以HTML格式生成的用户消息。 The messages are rendered by setting [innerHTML] of the viewer component. 通过设置查看器组件的[innerHTML]呈现消息。

These messages can contain links (in the form <a href="..."> ) with absolute URLs to other pages in the app. 这些消息可以包含具有指向应用程序其他页面的绝对URL的链接(格式为<a href="..."> )。 Currently, when you click one of the links, Angular loads the page anew just like you had clicked a link to an external website. 当前,当您单击链接之一时,Angular会重新加载页面,就像您单击指向外部网站的链接一样。

How do I get Angular to just navigate straight to the target component in the app instead of reloading the page? 我如何让Angular直接导航到应用程序中的目标组件,而不是重新加载页面?

Additional Info 附加信息

One idea I came up with was to check the html for absolute links, try to match them against the current host, and if they match, remove the absolute part to make them relative. 我想到的一个想法是检查html中的绝对链接,尝试将它们与当前主机匹配,如果匹配,则删除绝对部分以使其相对。 This didn't work though, and Angular still reloads the page when navigating to the link. 但是,这没有用,并且Angular在导航到链接时仍会重新加载页面。 I assume this is because there's no routerLink directive considering the message is just vanilla HTML. 我认为这是因为考虑到消息只是普通HTML,所以没有routerLink指令。 Maybe a workaround would be to intercept the link opening and pass it on to the router instead if it should be treated as a relative link? 可能的解决方法是拦截链接的打开并将其传递给路由器,而不是将其视为相对链接吗?

The reason these links have to be absolute and can't just be relative to begin with is because we have multiple portal apps the user can access via the same account which all share the same message center. 这些链接必须是绝对的,不能只是相对于开头,是因为我们有多个门户应用程序,用户可以通过同一个帐户共享同一个消息中心来访问该门户应用程序。 Some messages might link to an item in portal A, while others might link to items in portal B. This might seem a bit convoluted, but we have a very good reason for doing this which I can't explain in this question. 有些消息可能链接到门户网站A中的项目,而另一些消息则可能链接到门户网站B中的项目。这似乎有些令人费解,但是我们这样做的理由非常充分,我不能在这个问题中进行解释。

Figured it out! 弄清楚了!

First intercept the click event for links in the message content: 首先拦截邮件内容中链接的click事件:

<div [innerHTML]="message.Content"
     (click)="onContentClick($event)"
     class="content"></div>

Then handle the link with the router if the link's host matches the current host: 如果链接的主机与当前主机匹配,则使用路由器处理该链接:

onContentClick(e: MouseEvent) {
  if (e.target instanceof HTMLAnchorElement
      && e.target.host === location.host) {
    e.preventDefault();
    this.router.navigateByUrl(e.target.pathname);
  }
}

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

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