Angular 如何绑定值到补丁请求的复选框点击事件?

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

我正在开发 Angular 8 Web 应用程序,其中数据库中的设置为 true 或 false。我想在切换更改时使用 toggle/checkbox 元素更新该值 - 即立即发送请求。

我已将我的问题缩小到这样一个事实,即发送补丁请求时未设置我通过 [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);
      }
    )
 }

service.ts

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

我可以将请求包装在 TimeOut 中吗?还是那也有点差?有谁知道这是如何工作的?

使用反应形式。首先使用响应式表单,但尤其是对于此用例。然后你可以简单地做:

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(() => {});