Search code examples
angularionic-frameworkionic5

Change side menu items dynamically in Ionic 5


I'm migrating a project from ionic 3.2 to 5.14, and I'm having trouble using observables instead of events.

In the original code, after the user logged in, I changed the name and image of the sidemenu through events:

app.component.ts

this.events.publish('user:login', this.nomePrimeiro, Date.now());
this.events.publish('image:login', this.imagem, Date.now());

and on app.component.ts I wrote this:

events.subscribe('user:login', (user, time) => {
  Global.nomePrimeiro = user;
});

events.subscribe('image:login', (image, time) => {
  Global.imagem = image;
});

How to change this for Observables? I will need a service?


Solution

  • Create event service. In the EventService.ts:

    export class EventService {
            private dataObserved = new BehaviorSubject<any>('');
            currentEvent = this.dataObserved.asObservable();
            constructo(){}
            
            publish(param):void {
              this.dataObserved.next(param);
            }
    }
    

    For publishing the event from example page1:

    constructor(public eventService:EventService){}
        updatePost(){
        this.eventService.publish('post:updated');
        // or 
        this.eventService.publish({name: 'postupdate', value: 'value you need to pass'});
    } 
    

    In page 2:

    constructor(public eventService:EventService){
          this.eventService.currentEvent.subscribe(data=>{
         // here you can get the data or do whatever you want or data.name or data.value
        
        });
    }