Ionic2 declare global function?

Hello there. I have a cordova plugin, that after finish calls JS function, let’s call it initFinished() for example purpose. I can receive that call with pure JS by just declaring it - function initFinished(){}

How to declare such global function within Page component or service?

Thanks in advance!

I might be misunderstanding what you are asking for (sorry if I am!) but you can put that function in a shared service that you inject into other components - see my blog post here

Thanks @richardshergold, but this is not what i’m looking for. Thing is that i tried with service (export function) and it is not working in desired way.

I’m not calling this initFinished() function myself and i’m also not in control of the way how that call is made. Only thing i need is to receive that call and able to react on that.

For now, my workaround solution is to define in index.html pure js

function initFinished() {
        console.log('---> initFinished called');

        var myevent = new CustomEvent('initFinishedEvent');
        console.log('---> dispatching event');
        document.dispatchEvent(myevent);
    }

and then within page.ts catch that

constructor(public nav: NavController) {
    this.nav = nav;
    document.addEventListener('initFinishedEvent', this.startLoading, false);
  }

  startLoading() {
    console.log('---> called startLoading');

    ...
 } 

Definitely i don’t like this way, so looking for an option to declare alternative to pure js function in page component

I’m sure you figured this out by now, but I had the same issue and found this Stackoverflow that answered my question. I’m leaving this here for anyone who follows us. :slight_smile:

1 Like

Hi Cheaf, i have a similar situation, but the way you use does not work for me, Did you find any other way to solve the problem? thank you.

I believe what OP is asking for is something like window.MyPluginName.Register('initFinished', function() { ... });. I was using this in an Ionic2 app last year, but it doesn’t seem to be working anymore, and I’m unsure why. I don’t get any errors from calling .Register(), but I get an error when I try to call initFinished() saying window.MyPluginName.initFinished is not a function.