在同级组件之间共享数据(无法正常工作) [英] Sharing data between sibling components (not working as expected)

查看:77
本文介绍了在同级组件之间共享数据(无法正常工作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据从一个同级组件发送到另一个同级组件,但未按预期工作

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆