【发布时间】:2017-09-20 12:31:41
【问题描述】:
我的问题的简短解释:
到目前为止,我的 html 中有这行代码:
<pre class="preFormattedText" [innerHtml]="(project | async)?.Remarks"></pre>
然后我找到了有用的插件Linkify 和SO 上的这篇文章。所以我添加了一个新的管道组件:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'linkify' })
export class LinkifyPipe implements PipeTransform {
transform(link: string): string {
return this.linkify(link);
}
private linkify(plainText): string {
let replacedText;
let replacePattern1;
let replacePattern2;
let replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
replacedText = plainText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
return replacedText;
}
}
所以我将原来的代码行更新为
<pre class="preFormattedText" [innerHtml]="(project | async)?.Remarks | linkify"></pre>
但现在我得到了这个错误:
ERROR TypeError: 无法读取属性'replace' of null
我的代码的这一部分被突出显示
<h3 class="subtitleH3">{{ this.localizationService.localized['globalComment'] }}</h3>
<div>
<pre class="preFormattedText" [innerHtml]="(project | async)?.Remarks | linkify"></pre>
</div>
【问题讨论】:
-
您的第一次或第二次替换返回 null。你能找出是哪一个吗?
-
看起来你的管道没有获得纯文本参数的价值,如果你想转换你的异步数据为什么不做 (project | async | linkify)
-
@RobinDijkhof 如果我在管道内设置断点,则断点会被调用两次。一旦给定的 obj 为空,一旦它的内容是我想要链接的内容......我猜原因是内容异步?
-
是的,我想是的。构建一个简单的空检查。
-
@RobinDijkhof 谢谢你,我做到了