簡體   English   中英

如何將值綁定到Angular中補丁請求的復選框單擊事件?

[英]How to bind value to checkbox click event for patch request in Angular?

我正在使用Angular 8 Web App,其中DB中的設置為true或false。 我想在切換更改時使用切換/復選框元素更新該值-即,請求立即發送。

我將問題縮小到以下事實:發送補丁程序請求時未設置通過[ngModel] =“ selectedView”在視圖中設置的屬性,補丁程序沒有給切換提供足夠的時間進行設置財產。

如何延遲事件,以便設置selectedView屬性,然后成功更新對象? 如在網絡選項卡中顯示一個空的有效載荷對象。

我注意到如果在切換器旁邊設置一個按鈕並讓該事件(而不是切換器)離開該按鈕,則此方法有效。 但是我認為這對於我需要切換的功能來說有點過大了。 切換然后單擊按鈕對我來說是相當差的用戶體驗。

nav_bar.component.html

    <li *ngIf="config">
        <p><small>Show Match Hub {{ selectedView }}</small></p>
        <label class="switch">
            <input 
            type="checkbox"
            [(ngModel)]="selectedView"
            [checked]="config.hide_match === 1"
            (change)="config.hide_match = config.hide_match ? 1 : 0" value="hide_match"
            (click)="switchMatchHub(selectedView)"
            >
            <span class="slider"></span>
        </label>
    </li>

nav_bar.component.ts(單擊事件)

selectedView: any;

switchMatchHub(){
    const updateView = {
      'hide_match': this.selectedView
    }
    this.configService.showMatch(updateView)
    .subscribe(
      response => {
        console.log(response);
      }
    )
 }

服務

showMatch(newConfig: any){
    return this.http.patch<{data: Config}>(this.configURL + '/' + this.id, newConfig)
    .pipe(
      retry(1),
      catchError(this.handleError),
    );
  }

我可以將請求包裝在超時中嗎? 還是有點貧窮? 有誰知道它如何工作?

使用反應形式。 首先使用反應形式,但對於這種用例尤其如此。 然后,您可以簡單地執行以下操作:

this.formControl.valueChanges.pipe(
   // handle "monkey-clicking" the selectbox
   debounceTime(200), 
   // if the user clicks it on and back of again quickly, ignore it all together.
   distinctUntilChanges(),
   // Map it to your object notation 
   map(toggle => ({'hide_match': toggle})),
   // Switch map it to server uploads. SwitchMap cancels any previous requests in case the checkbox is changed, so the order of events doesn't screw up your server status.
   switchMap(updateView => this.configService.showMatch(updateView))
).subscribe(() => {});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM