I can't get the information outside of subscribe section with Observable and HttpClient in Angular

49 views Asked by At

My backend is working, but in the frontend I have the service:

getDoctorById(sId : number): Observable<Doctor>{ let url = this.baseURL+"/id/"+sId return this.httpClient.get<Doctor>(${url}); }

In my component:

let serverGetDoctor = this.doctorService.getDoctorById(this.selectedD); serverGetDoctor.subscribe(data=>{ this.sch.idDoctor = data; // here I get the correct information });

but here "outside" I can't get it

console.log("doctor schedule: "+ this.sch.idDoctor.name); // this line generates error: ERROR TypeError: Cannot read properties of undefined (reading 'name')

I tried changing the code, but any works:

opt 1: In the service put the .pipe and tap:

getDoctorById(sId : number): Observable<Doctor>{ let url = this.baseURL+"/id/"+sId return this.httpClient.get<Doctor>(${url}).pipe( tap( _ => console.log("obtuvo el doctor en service")) ); }

opt 2: In the component :

I tried to do it in other method, but out of method doesn't work serverGetDoctor.subscribe((data: Doctor) => this.asignarDoctor(data))

opt 3:

serverGetDoctor.pipe(map(data=>this.sch.idDoctor = data));

opt 4:

serverGetDoctor.pipe(tap(data=>{this.sch.idDoctor = data})).subscribe();

0

There are 0 answers