简体   繁体   中英

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

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

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

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
      
  }

Please help

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

setting id via component

addQuestions(test_id: number) {
  this.service.testId = test_id; 
}

and finally getting value

ngOnInit() {
 const testId = this.service.testId
 console.log(testId);
}

Hope this address your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM