Ionic2 new Events() or Events.setupEvents() (and examples) ;


#1

Hello,

I am coding a static method (class method) that is intended to be called during the platform initialization

this.platform.ready()
      .then(...)

I need to publish an event in the callback method, however, due to the method being static, the normal way of injection by constructor signature does not work.

there are two possible alternatives as I can see:
1: new Events().publish(…) , ( as you can see in the code below)
2, I checked the Events.d.ts; and found out that there is a class method Events.setupEvents()

static geoConfig(){
        BackgroundGeolocation.configure(
                  (loc) => {
                              // Shall I use New Events() here? or  Events.setupEvents
                              //new Events().publish(Cons.EVT_HI_GEO, new Position(loc.latitude,loc.longitude));
                              BackgroundGeolocation.finish(); // FOR IOS ONLY
                              BackgroundGeolocation.stop();},
                  (error) => {
                              new Events().publish(Cons.EVT_HI_GEO, new GeoError(error.code, error.message));
                              BackgroundGeolocation.finish(); // FOR IOS ONLY
                              BackgroundGeolocation.stop();},
                  Geo.config);
    }

my question: which one shall I use? what more, are there any example?

please advise,

thanks


#2

you are searching for this:


???


#4

Hi,

I got this error “TypeError: Cannot read property ‘publish’ of undefined”

here is my code:

in my ‘app.component.ts’

import { Events } from 'ionic-angular';

constructor(public events: Events){
  this.events.subscribe('blablabla', () => {
    // something
  });
}

in my ‘service’

import { Events } from 'ionic-angular';

@Injectable()
export class Something
...

constructor(public events: Events){}

myFunction() {
  // publish events not working
  this.events.publish(blablabla');
}

Did i miss something here?

Thanks.


#5

Also getting that type error; did you manage to fix it?


#6

The code in the post above yours works, so whatever it is that y’all are having trouble with, it hasn’t been shown here yet.


#7

I’m not sure what’s the problem with the other post. I’ve made several tests since and it seems like my issue is that I’m calling Events inside a Media.create()'s onStatusUpdate callback function, like so:

On https://ionicframework.com/docs/native/media/#create we have:

create(src, onStatusUpdate) where onStatusUpdate “A callback function to be invoked when the status of the file changes”.

So I made:

onStatusUpdate(status){
    console.log(status);
    console.log("event thrown");
    this.eventCtrl.publish('audio:stopped',status);
};

Which is called, and the console logs work, but when it reaches the last line there, it no event is published and I get a type error. I’ve made a thread about it here.