Cordova plugin - network interface issue

Downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface

Can’t use any global variable or call any other function inside the function

networkinterface.getIPAddress(function (ip) { alert(ip);});

If i use something like this

networkinterface.getIPAddress(function (ip) {
  alert(ip);
  this.test(ip);
});
test(x) {
  console.log("IP = "+ x);
}

I get an error

Error in Success callbackId: networkinterface1280836273 : TypeError: Cannot read property 'test' of null.

I get Ip alert properly but I can’t access it outside the function.
Also typerscript gives the error [ts] Cannot find name 'networkinterface'. any when i use the plugin. But it still compiles and works
Any idea how to solve the issue?

Read about this.

You should use arrow functions (AKA lambda functions in TS) to capture the meaning of this from the surrounding context (as @rapropos wanted to hint you above I guess). You’ll find a good explanation about this in the TypeScript documentation. In the context of your code sample it means to change it this way:

export class Test {
  // ...
  function loadIPAddress() {
    networkinterface.getIPAddress((ip) => {
      alert(ip);
      this.test(ip);
    });
  }

  function test(x) {
    console.log("IP = "+ x);
  }
  // ...
}
2 Likes

Thank you so much @rapropos and @iignatov. It worked like a charm.
Although i must say that this is quite confusing :stuck_out_tongue_winking_eye:

ok any update on [ts] Cannot find name 'networkinterface'. any

I tried this solution this solution but the comand
typings install cordova/plugins/networkinterface --ambient --save
can not find the desired file

I guess that there are no typing definitions for this plugin then, you could try using an ambient declaration to get rid of the error message (untested, but it should work):

declare var networkinterface: any;
1 Like

Yes, it works. Thanks again

TypeError Cannot read property ‘getIPAddress’ of undefined

Please see this answer on Stackoverflow.

still getting the error. You can check over there.