Angular4将自定义管道添加到异步值

时间:2017-09-20 12:31:41

标签: angular pipe linkify

对我的问题的简短解释:

直到现在我的html中有这行代码:

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

然后我在Linkify找到了有用的插件SO和这篇帖子。所以我添加了一个新的pipeComponent:

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>

但现在我收到了这个错误:

  

错误TypeError:无法读取null的属性'replace'

我的代码的这一部分会突出显示

<h3 class="subtitleH3">{{ this.localizationService.localized['globalComment'] }}</h3>
<div>
    <pre class="preFormattedText" [innerHtml]="(project | async)?.Remarks | linkify"></pre>
</div>

1 个答案:

答案 0 :(得分:0)

发现它,必须实现一个简单的空检查

相关问题