在 Angular 2 中调用环境(本机)特定的全局 javascript 函数

Call environment (native) specific global javascript functions in Angular 2

我正在 Angular 2 中开发一个 Web 应用程序(通过 angular-cli),它可以加载到本地移动应用程序中(在 iOS 和 Android ) 通过一个简单的 URL.

可以使用桥函数与本机应用程序交互。这些功能被添加到应用程序网络浏览器的全局范围内(因此在普通网络浏览器中不存在)。此类函数的一个示例是 echoNative(),其中 returns 有关本机平台的信息:

{
  "platform": "iOS",
  "message": "Native received Echo call"
}

在正常的 javascript 应用程序中(没有 angular),可以在 javascript 代码中包含这些函数而不会 angular-cli 抛出错误。

我有以下问题:

  1. 如何防止 angular-cli 在我使用这些功能时无法构建我的应用程序?
  2. 是否可以为这些函数编写一个模拟库,如果它们存在于全局范围内则加载这些函数,如果不存在则提供替换?
  1. 您应该 find/write 自己为这些函数键入定义。在 documentation 中查看有关声明文件的更多信息。最简单的示例类似于创建以下文件:

    // src/app/index.d.ts
    
    declare interface Window {
      // This will tell TypeScript, that such function exists on `window`, but won't provide implementation for it. So if there is no implementation somewhere else, TypeScript won't error, but it will fail in runtime.
      echoNative: () => { platform: string, message: string }; 
    }
    
  2. 是的,你可以像在 JS 中那样做(不要忘记从你的应用程序中导入这个文件,所以它包含在包中):

    // src/app/mocks.ts
    
    if (typeof window.echoNative === 'undefined') {
      window.echoNative = () => {
        // Your mock implementation here.
      }
    }