Angular 如何在整个角度应用程序中声明函数

Angular 如何在整个角度应用程序中声明函数,angular,typescript,angular-cli,Angular,Typescript,Angular Cli,我在Angular5中使用AngularCLI 1.5进行了以下设置 在打字中。d.ts declare interface String { toSentenceCase(): string; } declare function _debug(o, message?, type?): void; String.prototype.toSentenceCase = function () { return this.substring(0, 1).toUpperCase() +

我在Angular5中使用AngularCLI 1.5进行了以下设置

打字中。d.ts

declare interface String {
   toSentenceCase(): string;
}
declare function _debug(o, message?, type?): void;
String.prototype.toSentenceCase = function () {
    return this.substring(0, 1).toUpperCase() + this.substring(1);
};
function _debug(o, message?, type?) {
    console.log(o);
}
import './app/core/common';
在app/core/common.ts中

declare interface String {
   toSentenceCase(): string;
}
declare function _debug(o, message?, type?): void;
String.prototype.toSentenceCase = function () {
    return this.substring(0, 1).toUpperCase() + this.substring(1);
};
function _debug(o, message?, type?) {
    console.log(o);
}
import './app/core/common';
main.ts中

declare interface String {
   toSentenceCase(): string;
}
declare function _debug(o, message?, type?): void;
String.prototype.toSentenceCase = function () {
    return this.substring(0, 1).toUpperCase() + this.substring(1);
};
function _debug(o, message?, type?) {
    console.log(o);
}
import './app/core/common';
现在在我的组件中

console.log('something'.toSentenceCase()); // works
_debug(data); // ERROR ReferenceError: _debug is not defined

当函数被忽略时,为什么要执行原型声明?

\u debug
是在模块范围内定义的,不是全局的。它可以定义为
window
property,但这不适用于服务器端渲染


在现代JavaScript/TypeScript开发中,尤其是Angular开发中,不鼓励依赖globals。函数应该从模块导出,并在使用它的地方导入。

您是从
通用
文件导入,而不是从
导出
文件导入。示例
export const my_constant='value'
和它们在一个组件中
import{my_contant}从'../path\u到\u common'
但是问题是我在任何地方都使用它,所以几乎在所有文件中导入它都有点麻烦。。。与objectname相比,调用_debug非常方便。_debug(或者有什么方法?)在几乎所有文件中都使用
组件
可注入
,但将它们公开为全局文件不是一个好主意。为了将其称为_debugglobally,应将其定义为
窗口。_debug=…
。但正如前面提到的,它在服务器端会有问题。最好的做法是在这种情况下不要这样做,而是在每次使用时导入它。IDE可以为您自动处理自动导入,这就是导入不是问题的原因。虽然这是一个公认的答案,但我最终为它添加了一个javascript函数:(尚不知道在Agnular Universal中如何处理它)设置跨平台全局的唯一一致方法是
const global=eval('this'));global._debug=…
.eval在CSP中可能会失败,但在节点和浏览器中都可以工作。这让我想到,jquery global已经安装好了,为什么不使用它呢?我就是这么做的,$.myfunction每当我需要访问全局函数时,它确实会使开发和维护更加顺利