如何避免 Angular-2 为链接添加前缀“不安全"? [英] How to avoid adding prefix “unsafe” to link by Angular-2?

查看:15
本文介绍了如何避免 Angular-2 为链接添加前缀“不安全"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I am developing a mobile app using angular2 and ionic 2, I have 3 buttons for call, sms and email as below

          <a ion-button href="tel:{{contact.cellphone}}" color="primary">
            <ion-icon name="call"></ion-icon>
            Call
          </a>
          <a ion-button href="sms:{{contact.cellphone}}" color="secondary">
            <ion-icon name="text"></ion-icon>
            SMS
          </a>
          <a ion-button href="mailto:{{contact.email}}" color="dark">
            <ion-icon name="mail"></ion-icon>
            Email
          </a>

Call and email are working fine, but not sms, it seems angular adds unsafe: in-front of my expression and it will become like below

<a color="secondary" ion-button="" ng-reflect-color="secondary" class="button button-md button-default button-default-md button-md-secondary" ng-reflect-href="unsafe:sms:+16475374201" href="unsafe:sms:+16475374201"><span class="button-inner">

even I tried this

      <a ion-button [attr.href]="'sms:'+contact.cellphone" color="secondary">
        <ion-icon name="text"></ion-icon>
        SMS
      </a>

still same issue,

When I don't use angular binding it's working fine, for example like this

          <a ion-button href="sms:+1647654654" color="secondary">
            <ion-icon name="text"></ion-icon>
            SMS
          </a>

Although it's related to angular but also I checked my config.xml and sms is allowed there

<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />

Update

After using @Apuu solution it become like below

          <a ion-button [attr.href]="'sms:'+contact.cellphone | safeUrl" color="secondary">
            <ion-icon name="text"></ion-icon>
            SMS
          </a>

解决方案

You can create a pipe service to change unsafe url to safe url.

Create a pipe service called safe-url.pipe.ts.

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
  name: 'safeUrl'
})
export class SafeUrlPipe implements PipeTransform {
  constructor(private domSanitizer: DomSanitizer) {}
  transform(url) {
    return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
}
}

Then use in your view.
Example :

<a ion-button [src]="'some_url' | safeUrl" color="secondary">
     <ion-icon name="text"></ion-icon>
     SMS
</a>

NOTE : Don't forget to inject this pipe service in your app.module.ts

import { SafeUrlPipe } from './shared/safe-url.pipe'; //make sure your safe-url.pipe.ts file path is matching.

And in your node module declarations section.

@NgModule({ declarations: [SafeUrlPipe],...});

这篇关于如何避免 Angular-2 为链接添加前缀“不安全"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆