[英]Sharing data between sibling components (not working as expected)
我正在嘗試將數據從一個同級組件發送到另一個組件,但它沒有按預期工作
下面是 service.ts 文件
private _testIdSource = new Subject<number>();
test_id = this._testIdSource.asObservable();
sendTestId(test_id : number){
console.log(test_id);//showing data
this._testIdSource.next(test_id);
}
此組件將表單的輸入作為 id
addQuestions(test_id:number){
console.log(test_id);//showing data
this.service.sendTestId(test_id);
this.router.navigate(['/editTest']);
}
並且該組件應該接收數據並將其初始化為全局變量testId
但我很難將全局變量的值設置為接收到的數據
ngOnInit() {
this.service.test_id
.subscribe(
message=> {
if(message != null){
this.testId = message;
console.log('test_id value received -> '+this.testId);//showing data
}else{
console.log('null value received');
}
}
);
console.log(this.testId);//says undefined
}
請幫忙
您可以使用簡單的TypeScript Setter 和 Getter而不是 Observable(我們必須取消訂閱以防止內存泄漏)將值傳遞給兄弟組件。
服務.ts
test_id: number;
get testId(): string {
return this.test_id;
}
set testId(id): string {
this.test_id = id;
}
通過組件設置id
addQuestions(test_id: number) {
this.service.testId = test_id;
}
並最終獲得價值
ngOnInit() {
const testId = this.service.testId
console.log(testId);
}
希望這能解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.