global function in Ionic 2 / Angular 2

前端 未结 3 1696
粉色の甜心
粉色の甜心 2020-12-16 03:30

How can I setup a global function that can be accessed throughout all views?

In app.component.ts I added a simple method

  openShare() {console.log         


        
3条回答
  •  自闭症患者
    2020-12-16 04:07

    Just like @Sampath mentioned, one way would be to use a custom provider. But since you method is just a simple one, I think you can use Events instead. It'd be like this:

    In your app.component.ts file, subscribe to the new event:

    import { Events } from 'ionic-angular';
    
    constructor(public events: Events, ...) {
    
      // ...
    
      events.subscribe('social:share', () => {
    
        // your code...
        console.log("button clicked");
    
      });
    
    }
    

    And then in any other page, just publish the event to execute that logic:

    function anotherPageMethod() {
      this.events.publish('social:share');
    }
    

提交回复
热议问题