在 angular4 中访问本机 js 全局对象或从编译中排除单个打字稿行?

access native js global object in angular4 or exclude single typescript line from compiling?

在 ts 中我想保留一行 Javascript 代码原样,因为它使用了 tsc 未知的类型(没有 node_module 可用)但是在运行时,它存在于浏览器的全局 window 对象中。 有一个简单的解决方案吗? (通过注释即)。 我用angular4.

如果您不知道它的类型,请使用 any 类型。

const foo: any = window.globalVar

const foo = windows.globalVar as any

中所述,您可以为 window 或全局变量引入服务,以便使用 DI 处理此问题:

export const WINDOW = new OpaqueToken();

...
providers: [..., { provide: WINDOW, useFactory: () => window }]
...

constructor(@Inject(WINDOW) window) {
    window.foo();
}

window 不可用的环境中 WINDOW 提供程序可以替换为其他实现,例如noop foo.