运行 FormControl 的 valueChanges 事件的方法

Run Method on FormControl's valueChanges Event

我有以下用于 Angular 2 type-ahead 组件的代码:

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);
            }
        );

效果很好,但是我正在尝试向该事件添加加载动画,即动画在 FormControl 的值更改时开始,在返回数据时结束。

说到这里,有没有办法使用如下代码进入这个方法链?

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

如有任何帮助,我们将不胜感激。

这还没有经过测试,但它与我在我的应用程序中使用的代码类似...希望对您有所帮助:

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);
        this.startAnimation();
     },
     () => {this.completeAnimation()}
  );

startAnimation() {
   //start animation code here
}

completeAnimation() {
   //complete the animation here.
}

事实证明这真的很简单...要将自定义代码添加到开关映射中,您只需执行以下操作即可。

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()
    );

让我成功尝试的诀窍是 return 在你的函数之后请求。