P. Moloney P. Moloney - 2 months ago 14
TypeScript Question

Run Method on FormControl's valueChanges Event

I have the following code for an Angular 2 type-ahead component:

this.question["input"] = new FormControl();
this.question["input"].valueChanges
.debounceTime(400)
.switchMap(term => this.question['callback'](term))
.subscribe(
data => {
this.question["options"].length = 0;
this.question["options"].push(...data);
}
);


Which is working great, however I am Attempting to add a loading animation to this event, i.e. an animation starts when the FormControl's value changes, and ends when the data is returned.

With this said is there a way to tap into this method chain with code such as the following?

...
.valueChanges
/* Start Animation or Run Custom Function Here */
.switchMap(term => /* Run AJAX Here */)
.subscribe(
data => {
/* End Animation Here */
}
);
...


Any assistance is appreciated.

Answer

As it turns out this is really easy... To add custom code into the switch map you can simply do the following.

this.question["input"] = new FormControl();
this.question["input"].valueChanges
    .debounceTime(400)
    .switchMap(term => {
        // custom code can go here.
        this.customAnimationStart();
        return this.question['callback'](term);
    })
    .subscribe(
        data => {
            this.question["options"].length = 0;
            this.question["options"].push(...data);
        },
        failed => console.error("Request Failed", failed),
        () => this.customAnimationEnd()
    );

The trick that caught me up with this attempt was to return the request after your function(s).