我有一個設置複選框,許多不同的用戶可以同時使用。我輪詢服務器以每5秒獲取複選框的狀態。問題是,有時當我檢查一個框(併發出一個post請求)時,它正在解析get請求並且視圖正在更新。這基本上「錯過」了複選框點擊,並且當用戶單擊時未選中的複選框仍未選中。有沒有解決的辦法?有沒有辦法告訴我的可觀察的「嘿,當我檢查我的盒子時,停止更新來自請求的視圖」。我嘗試在click()函數開始時取消訂閱observable,然後重新訂閱,但更加嚴重。我的代碼用戶和獲取請求之間的衝突更新HTML視圖角度4
簡單的例子: 控制器:
ngOnInit(): void {
// get our data immediately when the component inits
this.checklistService.getchecklist()
.first() // only gets fired once
.subscribe(data => {
this.checklist = data;
});
// get our data every subsequent 5 seconds
this.subscription.add(
IntervalObservable.create(5000)
//.takeWhile(() => this.alive) // only fires when component is alive
.subscribe(() => {
this.checklistService.getchecklist()
.subscribe(data => {
this.checklist = data;
});
})
);
}
checkOrUncheck(outgoingItemCheck: ChecklistItem) {
if (outgoingItemCheck.CheckListStepId == null) {
console.log('null ItemId found at checklist with a description of: ' + outgoingItemCheck.description);
}
else {
if (outgoingItemCheck.Checked == null) {
outgoingItemCheck.Checked = true;
}
else {
outgoingItemCheck.Checked = !outgoingItemCheck.Checked; //switch from true to false, or false to true
}
this.checklistService.checkOrUncheck(outgoingItemCheck)
.then(checklistItemFromServer => {
this.checklistItem = checklistItemFromServer;
});
}
}
服務
getchecklist(): Observable<ChecklistItem[]> {
return this.http.get(this.checklistUrl).map(response => response.json());
}
HTML
<label class="custcol3 form-check-label columnchecklistheader columncentertext">
<div *ngIf="clItem.Checked; else notCheckBlock">
<input class="form-check-input" type="checkbox" checked="checked" (click)="checkOrUncheck(clItem)" value="" style="cursor: pointer;">
</div>
<ng-template #notCheckBlock>
<label>
<input class="form-check-input" type="checkbox" (click)="checkOrUncheck(clItem);" value="" style="cursor: pointer;">
</label>
</ng-template>
</label>
你可以擴展這是什麼意思? –
我需要一個簡單的代碼來幫助糾正它。 – sancelot
我添加了我的代碼,希望您能提供一些反饋 –