简体   繁体   English

如何通过 ngOnInit() 中的“发送消息/调用函数”在 Angular 中的兄弟组件之间传递数据?

[英]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.我想将消息从 ComponentA 发送到 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);这是代码-我的问题是,如果我从 componentA 的 html 文件调用 sendInfoToB()(事件挂接到按钮单击),那么我将在 componentB /getting console.log(this.check); 中收到消息。 and console.log(message);和控制台日志(消息); 's values in the console.. but when I call this.sendInfoToB(true);控制台中的值.. 但是当我调用 this.sendInfoToB(true); from componentA's ngOnInit() then I get no message in console for componentB.从 componentA 的 ngOnInit() 然后我在 componentB 的控制台中没有收到任何消息。 I want the message when I call from componentA's ngOnInit.当我从 componentA 的 ngOnInit 调用时,我想要消息。 How can I achieve that?我怎样才能做到这一点? Please help.请帮忙。 Thank you in advance.先感谢您。

ComponentA.ts 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消息.service.ts

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

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

    }
}

ComponentB.ts组件B.ts

constructor(private sibService: SiblingService,) {}

ngOnInit() {
        
        this.sibService.sendMessage.subscribe((message) => {
            this.check = message;
            console.log(this.check);
            console.log(message);
        });
    }

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.创建组件 A 并发送消息,然后创建组件 B 并订阅新消息。 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.最简单的策略是使用 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.另一种方法是在初始化发生后发送消息,就像点击事件一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM