2
votes

I am trying to share data from one component to another using BehaviorSubject but when i subscribe to observable in the Target Component it returns null

This is my Service Class

 private apiData = new BehaviorSubject<Patient>(null);
 public apiData$ = this.apiData.asObservable();

getSinglePatient(id) {

this.loadToken();
let headers = new HttpHeaders().set('Authorization', this.authToken);
return this.http.get('http://localhost:3000/api/patient/' + id, { headers: 
headers });
}

setData(data) {

  this.apiData.next(data);

}

This is my Primary Class where i get data

 getSinglePatient(id: any) {

  this.patientService.getSinglePatient(id).subscribe((data: any) => {
  this.patients = data; //<-- Patients is an Array 
  this.patientService.setData(data);
  this.router.navigate(['/records']);
  console.log(data);

});

This is my Target Class where I want to Display/Retrive Data

patient: Patient;
constructor(private patientService: PatientService) {

this.patientService.apiData$.subscribe(patient => console.log(patient));
}

This is my Console Output

Log

I Referred to this example

Not sure whats wrong as this the first time I'm doing this. Thanks.

1
where did you declared provider for patientService ? - Sunil Singh
@SunilSingh I'm declaring it in the app.module and in both Priamry Class and Target Class - Shivam Sood
Do not provide in Primary Class and Target Class. - Sunil Singh
@SunilSingh Oh wow it actually worked. Can you Please Explain why did U mentioned it? and can u please write it as an answer so that i can mark it - Shivam Sood
Each providers creates the new instance of class. If you want to communicate through service class then its not necessary to have same reference of Object. If provide in multiple places, all will have their own version of class. - Sunil Singh

1 Answers

1
votes

You need to set apiData$ once you assign ,

setData(data) {
  this.apiData.next(data);
  this.apiData$ = this.apiData.asObservable();
}

EDIT:

You do not necessarily have to do the above, Just have the service configured in the app.module level.Not in each of the class since they will create an instance each time, the values will be vanished.