【问题标题】:Angular4 add custom pipe to async valueAngular4将自定义管道添加到异步值
【发布时间】:2017-09-20 12:31:41
【问题描述】:

我的问题的简短解释:

到目前为止,我的 html 中有这行代码:

<pre class="preFormattedText" [innerHtml]="(project | async)?.Remarks"></pre>

然后我找到了有用的插件LinkifySO 上的这篇文章。所以我添加了一个新的管道组件:

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 谢谢你,我做到了

标签: angular pipe linkify


【解决方案1】:

找到了,必须实现一个简单的空检查

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-03
    • 2018-06-18
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 2017-04-04
    • 2017-07-26
    • 1970-01-01
    相关资源
    最近更新 更多