0

我有一個角2型預組件下面的代碼:上FormControl的valueChanges事件運行方法

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

任何協助表示讚賞。

回答

0

事實證明這是很容易的......要添加自定義代碼到開關映射中,您可以簡單地執行以下操作。

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的功能(S)後的請求。

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. 
} 
+0

謝謝你的意見,但這不是我正在尋找的。在你的代碼中,'this.startAnimation();'只會在AJAX調用返回數據**後觸發**,並且一旦代碼在data => {...}塊中運行。 –

+0

如上所述,最好在always函數中使用'this.completeAnimation()''()=> {...}',這樣動畫就會結束,即使AJAX通話失敗。 –

+0

然後將開始動畫移動到您撥打http呼叫的地方...... –