Access global variable?


#1

I have directive written in angular 2 typescript.

import {Injectable} from 'angular2/core';


@Injectable()
export class EnvironmentService {
  constructor () {
  }

  getEnvironment() {
    if (typeof cordova !== "undefined") {
      return 'ionic';
    }
    return 'browser';
  }
}

However, this runs fine but everytime Typescript trys to compile, it give me an error like this

TypeScript error: /Users/me/woot/myproject/app/shared/environment.service.ts(13,16): Error TS2304: Cannot find name 'cordova'.

Still learning TypeScript and seems when accessing global variable like ‘cordova’, seems it’s not liking it when compiling. What’s the best practice to access the global variable?


#2

To answer your direct question, at top level in that file you can say declare var cordova:any;.

However, Ionic provides a Platform that provides this functionality, and I would use that instead (especially because of the timing issues at startup):

constructor(plat:Platform) {
  plat.isReady().then(() => {
     if (plat.is('cordova')) {
       // we are on device
    }
  });
}

#3

Yeah, I do know that. I actually haven’t included in this example, but I’m using Ionic 2 for desktop & web as well. :slight_smile: Thanks!


#4

Something to remember, though the typescript compiler may “yell” at this, it will still compile and allow you to run your app.


#5
declare var electron:any;

this worked.
yeah, it did run with Errors, but that’s just ugly.


#6

Personally I really wish this wasn’t the default behavior. noEmitOnError and noImplicitAnyhave found many many bugs for me before runtime, eliminating lots of frustrating fighting with JavaScript.