Global javascript functions for call environment (native) in Angular 2

I am developing a web application in Angular 2 (via angular-cli), which can be downloaded into my own mobile application (on iOS and Android) using a simple URL.

Using bridge functions, you can interact with a native application. These features are added to the global scope in the web browser of the application (and therefore do not exist in the normal web browser). An example of such a function is echoNative()that returns information about its own platform:

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

In a regular javascript application (without angular) it is possible to include these functions in your javascript code without metallocation errors angular-cli.

I have the following questions:

  • How can I prevent angular-clidue to the inability to create my application when I use these features?
  • Is it possible to write a mock library for these functions that loads functions if they exist in the global scope and provides a replacement if they do not?
+4
source share
1 answer
  • You must find / write type definitions for these functions. For more information about declaration files, see the documentation . The simplest example would be to create the following file:

    // 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 }; 
    }
    
  • Yes, you can do it the same way as in JS (do not forget to import this file from your application, therefore it is included in the package):

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

Source: https://habr.com/ru/post/1665403/


All Articles