I'm currently trying to show a simple loader on my search bar while the searching is taking place. I have planned to set a variable in the subscribe callback on the valueChanges
observable from my form control to a value "loading", and to set it to an empty string in the complete callback. However, the complete callback is never called.
I have also tried adding a callback to finally on the observable, but it is also never called.
My code:
searchBox: Control = new Control();
loadingClass: string = "";
constructor() {
this.searchBox.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.subscribe((text: string) => {
this.imageSearch = text;
this.loadingClass = "loading";
}, (err: Error) => {
console.log(err);
}, () => {
this.loadingClass = "";
console.log("test");
});
}
The ValueChanges is an event raised by the Angular forms whenever the value of the FormControl, FormGroup or FormArray changes. It returns an observable so that you can subscribe to it. The observable gets the latest value of the control. It allows us to track changes made to the value in real-time and respond to it.
Both FormControls and FormGroups expose an observable called valuesChanged . By subscribing to this observable we can react in real-time to changing values of an individual form control, or a group of form controls.
A FormGroup aggregates the values of each child FormControl into one object, with each control name as the key. It calculates its status by reducing the status values of its children. For example, if one of the controls in a group is invalid, the entire group becomes invalid.
It's normal since the observable is never completed. The valueChanges
allows you to receive value from your search box. In fact, you want to be notified when the search action is complete.
So I would try something like that, assuming that the searchImage
actually does the search and return an observable:
constructor() {
this.searchBox.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.flatMap((text:string) => { // <-------
this.loadingClass = "loading";
return this.searchImage(text);
})
.subscribe((searchResult) => {
this.imageSearch = searchResult;
this.loadingClass = ""; // <----
}, (err: Error) => {
console.log(err);
});
}
See this article for the use of the flatMap
operator:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With