簡體   English   中英

如何通過 ngOnInit() 中的“發送消息/調用函數”在 Angular 中的兄弟組件之間傳遞數據?

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

我想將消息從 ComponentA 發送到 ComponentB。 我正在為此使用服務。 這是代碼-我的問題是,如果我從 componentA 的 html 文件調用 sendInfoToB()(事件掛接到按鈕單擊),那么我將在 componentB /getting console.log(this.check); 中收到消息。 和控制台日志(消息); 控制台中的值.. 但是當我調用 this.sendInfoToB(true); 從 componentA 的 ngOnInit() 然后我在 componentB 的控制台中沒有收到任何消息。 當我從 componentA 的 ngOnInit 調用時,我想要消息。 我怎樣才能做到這一點? 請幫忙。 先感謝您。

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);
}

消息.service.ts

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

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

    }
}

組件B.ts

constructor(private sibService: SiblingService,) {}

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

這很可能與操作順序有關。 創建組件 A 並發送消息,然后創建組件 B 並訂閱新消息。 由於您使用的是主題,因此它只會為您提供訂閱發送的消息。

最簡單的策略是使用 BehaviorSubject。

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

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

    }
}

另一種方法是在初始化發生后發送消息,就像點擊事件一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM