在兄弟组件之间共享数据(未按预期工作) [英] Sharing data between sibling components (not working as expected)
问题描述
我正在尝试将数据从一个同级组件发送到另一个,但它没有按预期工作
I am trying to send data from one sibling component to another but it is not working as expected
下面是service.ts文件
Below is the service.ts file
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
this components takes the input from a form as id
addQuestions(test_id:number){
console.log(test_id);//showing data
this.service.sendTestId(test_id);
this.router.navigate(['/editTest']);
}
这个组件应该接收数据并将其初始化为全局变量 testId
但我很难将全局变量的值设置为接收到的数据
and this component is supposed to receive the data and initialize it to a global variable testId
but i am having difficulty in setting the value of global variable to the received data
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(我们必须取消订阅以防止内存泄漏).
You can pass value to sibling components using simple TypeScript Setter and Getter instead of an Observable (which we must need to unsubscribe to prevent memory leak).
service.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);
}
希望这能解决您的问题.
Hope this address your issue.
这篇关于在兄弟组件之间共享数据(未按预期工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!