【问题标题】:Run Method on FormControl's valueChanges Event在 FormControl 的 valueChanges 事件上运行方法
【发布时间】:2016-09-27 16:48:57
【问题描述】:

我有以下代码用于 Angular 2 预输入组件:

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 */
        }
    );
...

感谢任何帮助。

【问题讨论】:

    标签: angular typescript observable angular2-forms angular2-animation


    【解决方案1】:

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

    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.startAnimation(); 只会在 AJAX 调用返回数据之后触发,并且会在 data => { ... } 块中的代码运行后结束。
    • 说到这里,最好在always函数中加上this.completeAnimation()-() => { ... },这样即使AJAX调用失败,动画也会结束。跨度>
    • 是的,这会起作用,但同样不理想,因为这可能不是使用该 http 请求的唯一组件/服务,如果其他组件/服务需要动画,它们将不会有相同的动画一点也不。我将创建一个带有动画的单独 http 服务作为解决方法,但我会继续寻找这个问题的答案......再次感谢。
    【解决方案2】:

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

    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 请求。

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      相关资源
      最近更新 更多