Change sidemenu items in Ionic 5

Asked

Viewed 78 times

0

I am migrating a project from Ionic 3.2 to 5.14, and am having difficulties to use observables instead of Events.

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

login.pages.ts

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

and in the app.componentts. I put this on:

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

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

How to do the same with Observables?

1 answer

1


Apparently you are dealing with login event. In this case, it is advisable to use the Guard. More details here.

Anyway, to communicate between two Components you can create an intermediate service. For example, create the login.service.ts:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs';

@Injectable()
export class LoginService {

  // Observable string sources
  private userSource = new Subject<string>();
  private imageSource = new Subject<string>();

  // Observable string streams
  user$ = this.userSource.asObservable();
  image$ = this.imageSource.asObservable();

  // Service message commands
  anunciarUsuario(user) {
    this.userSource.next(user);
  }

  anunciarImagem(image) {
    this.imageSource.next(image);
  }
}

There in login.pages.ts:

constructor(private userService: UserService) {}

anunciarUsuario() {
    let usuario = { user: this.nomePrimeiro, time: Date.now() };
    this.userService.anunciarUsuario(usuario);
  }

anunciarImagem() {
    let image = { image: this.imagem, time: Date.now() };
    this.userService.anunciarImagem(imagem);
  }

And finally, in the app.componentts.:

  userSubscription: Subscription;
  imageSubscription: Subscription;


  constructor(private loginService: LoginService) {
    this.userSubscription = loginService.user$.subscribe(
      user => {
        Global.nomePrimeiro = user.user;
    });
    this.imageSubscription = loginService.image$.subscribe(
      image => {
        Global.imagem = image.image;
    });
  }

I created 2 services because their code was like this, but I believe that only 1 service could send the user and image data, making everything much simpler. Anyway, this should work, but it is also suggested to use the Guards to protect the routes of your application.

And you can also consult here for more details on communication between componenetes.

  • Thank you, I solved the problem with a single service, but within what you put.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.