0

I am trynig to send data from one component to another but it gives me undefined always !

This is my services.ts :

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

 @Injectable({
   providedIn: 'root'
 })
export class DataService {

 constructor() { }

private subjectDossierNumber = new Subject<any>();

sendDossierNumber( dossierNumber : string){
  this.subjectDossierNumber.next(dossierNumber);
}

getDossierNumber() : Observable<any>{
 return this.subjectDossierNumber.asObservable();
}
}

This is the component which send data :

 dossierNumber:string;
 constructor(private dataService : DataService){}
 ngOnInit(){
   this.dossierNumber="2145"}
  createNewRequest() { this.dataService.sendDossierNumber(this.dossierNumber); }

And This is the component which receive data :

dossierNumber : string;
constructor(private dataService : DataService){}
ngOnInit() { 
  this.dataService.getDossierNumber().subscribe(data => {this.dossierNumber = data;})
  }

It is going well in the sendDossierNumber() method but in the getDossierNumber() method the data is always undefined. Can anyone know what is the problem please ?

hiba nebli
  • 107
  • 2
  • 18

2 Answers2

1

My first guess is that you are using a Subject, and not a BehaviorSubject. The main difference is that a Subject does not return the initial value when you start subscribing to it, but a BehaviorSubject does.

With a Subject

  • If you start subscribing, and then send a new message, the message will be received.
  • If you send a message, and start subscribing afterwards, you will not get the current state (value) of the Subject.

With a BehaviorSubject

  • If you start subscribing, and then send a new message, the message will be received.
  • If you send a message, and start subscribing afterwards, you will get the current state (value) of the BehaviorSubject.

Here are some useful questions for further reading:

John
  • 10,165
  • 5
  • 55
  • 71
0

Try to use private subjectDossierNumber = new BehaviorSubject<string>(''). Consider ReplaySubject if you want the subject to hold more than one value.