Condivisione dei dati tra componenti di pari livello (non funziona come previsto)

Aug 23 2020

Sto provando a inviare dati da un componente di pari livello a un altro ma non funziona come previsto

Di seguito è riportato il file 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);
  }

questo componente prende l'input da un form come id

addQuestions(test_id:number){
    console.log(test_id);//showing data
    
    this.service.sendTestId(test_id); 
    this.router.navigate(['/editTest']);    
    
  }

e questo componente dovrebbe ricevere i dati e inizializzarli su una variabile globale testIdma ho difficoltà nell'impostare il valore della variabile globale ai dati ricevuti

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
      
  }

Per favore aiuto

Risposte

2 KamranKhatti Aug 23 2020 at 09:43

Puoi passare il valore ai componenti di pari livello utilizzando semplici TypeScript Setter e Getter invece di un Observable (che dobbiamo annullare l'iscrizione per evitare perdite di memoria).

service.ts

test_id: number;

get testId(): string {
  return this.test_id;
}

set testId(id): string {
  this.test_id = id;
}

impostazione dell'ID tramite componente

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

e infine ottenere valore

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

Spero che questo risolva il tuo problema.