Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
How to pass data between sibling components in Angular, by 'sending the message/calling the function' from ngOnInit()?

I want to send message from ComponentA to ComponentB. And I am using service for that. Here is the code- My problem is if I call sendInfoToB() from componentA's html file (event hooked to a button click), then I'm recieving the message in componentB /getting console.log(this.check); and console.log(message); 's values in the console.. but when I call this.sendInfoToB(true); from componentA's ngOnInit() then I get no message in console for componentB. I want the message when I call from componentA's ngOnInit. How can I achieve that? Please help. Thank you in advance.

ComponentA.ts

constructor(private siblingService: SiblingService,) {}

public dataX: boolean = false;
someFunc(){
//some calculation returning true
  this.dataX = true;
}

ngOnInit() {
    this.someFunc();
    this.sendInfoToB();
}

sendInfoToB() {
    this.siblingService.communicateMessage(dataX);
}

message.service.ts

export class SiblingService {
    sendMessage = new Subject();
    constructor() {}

    communicateMessage(msg) {
        this.sendMessage.next(msg);

    }
}

ComponentB.ts

constructor(private sibService: SiblingService,) {}

ngOnInit() {
        
        this.sibService.sendMessage.subscribe((message) => {
            this.check = message;
            console.log(this.check);
            console.log(message);
        });
    }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

More than likely this has to do with order of operations. Component A is created and sends the message, then Component B gets created and subscribes to new messages. Since you are using a Subject it only gives you messages sent after you subscribe to it.

The easiest strategy to this is to use a BehaviorSubject.

export class SiblingService {
    sendMessage = new BehaviorSubject();
    constructor() {}

    communicateMessage(msg) {
        this.sendMessage.next(msg);

    }
}

The other way is to send the message after the init happens, like on a click event.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda