Ionic2添加自定义扩展方法

时间:2016-12-10 08:29:51

标签: angular ionic2 extension-methods

我想将扩展方法添加到本机String类型。

的字符串-extension.ts:

interface String {
    toSlug(): string;
}

String.prototype.toSlug = function () {
    var str = this.toLowerCase();
    str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ  |ặ|ẳ|ẵ/g, "a");
    str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e");
    str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i");
    str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ  |ợ|ở|ỡ/g, "o");
    str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
    str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
    str = str.replace(/đ/g, "d");
    str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g, " ");
    str = str.replace(/-+-/g, " ");
    str = str.replace(/^\-+|\-+$/g, "");
    return str.trim();
}

用法:

public slug: string = "UTF String".toSlug();

VS Code建议正常运行没有任何问题。但是在ionic serve之后它会抛出String.toSlug is not a function

以下是我的CLI版本:

Cordova CLI: 6.4.0 Ionic Framework Version: 2.0.0-rc.3 Ionic CLI Version: 2.1.13 Ionic App Lib Version: 2.1.7 Ionic App Scripts Version: 0.0.45 ios-deploy version: Not installed ios-sim version: Not installed OS: Windows 10 Node Version: v6.9.1

任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:1)

我找到了答案。解决方案是将导入扩展文件导入app.module.ts

import '../extentions/string.ts';
import '../extensions/array.ts';
...

将原型更改为此(角度2 +):

String.prototype.toSlug = function (this:string) { ... }

问题是离子-app-script模块在编译时不包含文件。

相关问题