【问题标题】:Sharing data between sibling components (not working as expected)在兄弟组件之间共享数据(未按预期工作)
【发布时间】:2020-12-12 03:57:43
【问题描述】:

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

下面是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
      
  }

请帮忙

【问题讨论】:

    标签: angular typescript components


    【解决方案1】:

    您可以使用简单的TypeScript Setter and Getter 而不是 Observable(我们必须取消订阅以防止内存泄漏)将值传递给兄弟组件。

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

    希望这能解决您的问题。

    【讨论】:

      猜你喜欢
      • 2021-01-04
      • 2018-02-17
      • 2017-10-01
      • 1970-01-01
      • 2017-09-14
      • 2017-10-11
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多