Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda