@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 have a scenario when the user types text I have to hit API and save the typed data. As it will be inefficient to hit API for every keystroke. so I have used 'fromEvent' RxJs operator to debounce for a second.
The thing is that I can't update HTML(because I have simplified the HTML here but in my project its a collapsible panel, it will cause few HTML elements to disappear which I don't want) as I type data So that's the reason I store the response in a temporary variable 'recentResponse' and upon clicking Save button I update HTML.
But the problem here is if user types very fast and clicks Save button, it takes few seconds until Subscribe is finished, until then 'recentResponse' is undefined thus 'patientInformation' never gets updates(so does HTML).
How can I wait until Subscribe is finished inside onSave()? I need to wait until 'recentResponse' has some response.