2

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.

Shivam
  • 3,514
  • 2
  • 13
  • 27

1 Answers1

1

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.

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • I did this change and now I'm getting an error saying 'Uncaught (in promise): TypeError: Cannot read property 'subscribe' of undefined TypeError: Cannot read property 'subscribe' of undefined' – Shivam Oct 14 '18 at 04:32