Angular CLI - How to share prototype functions across the application

前端 未结 3 879
长发绾君心
长发绾君心 2021-01-17 13:07

I need to have some global prototype functions on the string class. Eg.

string.prototype.trimWhiteSpaces = function () {
  return this.replace(/ +/g, \'\');
         


        
3条回答
  •  醉话见心
    2021-01-17 14:13

    You can simply declare such interface as global and import this file to your app.module.

    So your file e.g. prototypes.ts should look like this:

    declare global {
        interface String {
            trimWhiteSpaces(): string;
        }
    }
    
    if (!String.prototype.trimWhiteSpaces)
        String.prototype.trimWhiteSpaces = function (): string {
            return this.replace(/ +/g, '');
        }
    }
    

    app.module.ts:

    import './prototypes.ts';
    

提交回复
热议问题