@Component({
selector: 'note-consultant',
template: '<div>
<div>{{patientInformation}}</div>
<textarea #textElemRef></textarea>
<button (click)="onSave()">Done</button>
</div>'
})
export class NoteConsultantComponent implements OnInit, AfterViewInit {
recentResponse:any;
patientInformation:any;
@ViewChild('textElemRef') textElemRef: ElementRef;
ngAfterViewInit(): void {
fromEvent(this.textElemRef.nativeElement, 'keyup').pipe(
map((event: any) => {
return event.target.value;
})
,debounceTime(1000)
).subscribe((text: string) => {
let request = this.buildRequestItem(text);
this.patientService.saveProblemNotes(request).subscribe((resp: any) => {
if (resp.error) {
console.log(resp.error);
return;
}
//update response in temp variable...
this.recentResponse = resp.problemText;
}
});
}
onSave() {
if (this.recentResponse != null) {
//when clicking save button update DOM
this.patientInformation = this.recentResponse;
}
//Reset temp variable
this.recentResponse = null;
}
}
I encountered a scenario where I needed to make an API call and save data whenever the user types text. To avoid hitting the API for every keystroke, I implemented the 'fromEvent' RxJs operator with debounce for a second.
In my case, I couldn't directly update the HTML while typing because it would cause certain elements to disappear, so I stored the response in a temporary variable called 'recentResponse'. When the Save button is clicked, I update the HTML based on this variable.
However, I faced an issue when users type fast and click Save immediately. It takes a few seconds until the Subscribe operation is finished, during which 'recentResponse' remains undefined, preventing 'patientInformation' and the corresponding HTML from updating.
Is there a way to ensure that the onSave function waits until the Subscribe operation is completed and 'recentResponse' has a valid response before proceeding?