Angular - iframe、DomSanitizer模块、单例

Angular开发中的几个小知识点

Angular使用iframe加载外部网站

问题

项目中,需要使用iframe来加载一个外部网页,但src被Angular的默认安全策略所禁止,无法加载网页。

解决

在Angular中,可以使用iframe用来加载一个外部链接地址,但是src需要使用@angular/platform-browser中的DomSanitizer模块中的sanitizer.bypassSecurityTrustResourceUrl(url)方法来特殊处理,因为Angular中有默认的安全规则会阻止链接的加载。

一个例子:

html:

<!--这样无法正常加载网页,被安全策略禁止-->
<iframe [src]="link" width="100%" height="100%" frameborder="0" align="center"></iframe>
<!--需要这样使用-->
<iframe id='MainIframe' [src]="trust(link)" width="100%" height="100%" frameborder="0" align="center"></iframe>
<!--或直接处理-->
<iframe id='MainIframe' [src]="sanitizer.bypassSecurityTrustResourceUrl(link)" width="100%" height="100%" frameborder="0" align="center"></iframe>

ts:


//引入DomSanitizer模块
import { DomSanitizer } from '@angular/platform-browser';

...

link:string = 'http://www.baidu.com';

constructor(private sanitizer: DomSanitizer) {
console.log('Hello IframeFull Component');
}

...

trust(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

测试时间:2017-04-26
使用Angular版本: 2.2.1

Angular单例

angular2一个单例的写法

import {Injectable} from '@angular/core';
import {UserInterface} from "../interface/index";

/**
* 这是一个单例模式的config,用于共享全局变量
**/
@Injectable()
export class Config {
public mode = 'dev'; //运行模式 dev or release
// public hostURL = 'https://cnodejs.org/api/v1'; //http请求前缀
public hostURL = 'http://ionichina.com/api/v1'; //http请求前缀
// public hostURL = 'http://localhost:8100/api'; //http请求前缀
public isIonic = true;

public pageLimit = 15; //每页多少
public DRAFTS_URL = '/data/drafts.json'; //草稿本地地址
public token: string = ''; //如果已经登录,存放token,请和localstorage.get('token')同步
public loginUser: UserInterface; //如果已经登录,存放登录用户信息,请和本地存储保持同步
static instance: Config;
static isCreating: Boolean = false;

constructor() {
if (!Config.isCreating) {
throw new Error("You can't call new in Config Singleton instance!");
}
}

static getInstance() {
if (Config.instance == null) {
Config.isCreating = true;
Config.instance = new Config();
Config.isCreating = false;
}
return Config.instance;
}
}

ionic2在scss中访问主题颜色

通过在scss中引用主题颜色,可以增加程序的可维护性,当程序的主题颜色更改时,引用的地方随之自动更改。

使用background-color: map-get($colors, primary)来引用在主题中定义的颜色。

示例:

.progress-inner {
min-width: 15%;
white-space: nowrap;
overflow: hidden;
height: 4px;
border-radius: 10px;
background-color: map-get($colors, primary);
}