Since Ionic 5 came out I decided to try it out. I have learned that they are now using Oberservables instead of Events. I have the following event in my code:
Subscribing like this in my constructor:
this.events.subscribe('go-to-slide', (tab, id) => {
this.currentID = id;
if (id === 0) {
this.showLeftButton = false;
}
// if data has already been loaded
if (this.dataLoadedFlag === true) {
// from tile
if (this.globalVariableService.comesFromTileClick === true) {
if (this.globalVariableService.languageChanged === true) {
this.languageChanged = false;
this.slidesComponent.slides.slideTo(id, 0);
this.getSectorTitlesAndColours();
this.dataLoadedFlag = true;
this.updateHeader(id);
} else if (this.globalVariableService.languageChanged === false) {
this.updateHeader(id);
}
} else if (this.globalVariableService.comesFromTileClick === false) {
}
} else if (this.dataLoadedFlag === false) {
if (this.globalVariableService.comesFromTileClick === true) {
this.slidesComponent.slides.slideTo(id, 0);
this.getSectorTitlesAndColours();
this.dataLoadedFlag = true;
this.updateHeader(id);
} else if (this.globalVariableService.comesFromTileClick === false) {
this.getSectorTitlesAndColours();
this.showRightButton = true;
this.dataLoadedFlag = true;
this.updateHeader(0);
}
}
const tempGlobalVariableService = this.globalVariableService;
// tslint:disable-next-line: only-arrow-functions
setTimeout(function() {
tempGlobalVariableService.comesFromTileClick = false;
}, 500);
});
}
and publishing the event like this in different components/methods:
this.events.publish('go-to-slide', 1, 1);
I tried different ways to change this code to observable but I can't seem to find the right way.
Anyone tried this already and can help me out? Thanks
I have already answered it here https://stackoverflow.com/a/60246906/2405040
You can create a small service for that like:
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class GlobalFooService {
private fooSubject = new Subject<any>();
publishSomeData(data: any) {
this.fooSubject.next(data);
}
getObservable(): Subject<any> {
return this.fooSubject;
}
}
For a complete example, please refer to the other answer.
And by the way, to discuss on this comment:
I have learned that they are now using Oberservables instead of Events
This is not that true. Basically, they have removed the Events
service from Ionic 5 and asking us to use the Observables
instead, by creating our own similar implementation.
They might have been using the Events
internally since Ionic 3. But since Ionic 4that, they have removed the internal usage as Obersables has grown so much and it's a kind of backbone to both Angular & Ionic.