我有一个切换开关,当它被触发时,它会发出http补丁请求。下面你可以看到它是什么样子的:
模板:
<div id="toggle-status-btn-container">
<div class="slider" [ngClass]="{'to-right': !shopIsOpen}"></div>
<div class="label-container">
<label class="store-opened" (click)="updateShopSlotsStatus(true)" [ngClass]="{'toggled-opened-text': !shopIsOpen}">OPENED</label>
</div>
<div class="label-container">
<label class="store-closed" (click)="updateShopSlotsStatus(false)" [ngClass]="{'toggled-closed-text': !shopIsOpen}">CLOSED</label>
</div>
</div>
它工作得很好,但到目前为止,用户可以垃圾邮件这个切换开关,触发多个http请求。
我能做些什么来防止这种行为?如果用户正在发送垃圾邮件切换开关,我不想触发http请求。也许有一种方法可以只触发最后一个?由于我是RxJ的新手,我真的不知道如何解决这个问题。
下面是在组件.ts中由click事件调用的方法:
updateShopSlotsStatus(isOpen: boolean){
this.shopIsOpen = isOpen;
this.apiService.updateShopSlotsStatus(isOpen, this.weekDay).subscribe();
}
以及服务文件中的http请求:
updateShopSlotsStatus(isOpen: boolean, weekDay: string){
const endpoint = this.url + "shipping/" + this.webzineId + "/delivery_slots" + "/";
return this.http.patch(endpoint, {"slots": { [weekDay] : { "enabled": isOpen }}});
}
提前谢谢。
发布于 2021-06-14 17:27:49
您可能希望像在this StackBlitz中那样组合使用BehaviorSubject
和switchMap
。
在这里,我将打开和关闭按钮绑定到一个函数,该函数更改BehaviorSubject
的值,如下所示:
模板:
<button
(click)="updateShopSlotsStatus(true)"
[ngClass]="{'selected': shopSlotStatus$ | async}"
>
OPEN
</button>
<button
(click)="updateShopSlotsStatus(false)"
[ngClass]="{'selected': !(shopSlotStatus$ | async)}"
>
CLOSED
</button>
ts:
updateShopSlotsStatus(isOpen: boolean) {
this.shopSlotStatusSubject$.next(isOpen);
}
然后,您可以观察BehaviorSubject
上的更改,如下所示:
private shopSlotStatusSubject$: BehaviorSubject<
boolean
> = new BehaviorSubject(false);
// shared so only one subscription is maintained
private readonly shopSlotStatus$ = this.shopSlotStatusSubject$
.asObservable()
.pipe(share());
readonly changeSlotStatus$ = this.shopSlotStatus$.pipe(
// you could introduce a debounceTime here if you wanted
// debounceTime(500),
tap(() => (this.changingStatus = true)),
// faked API call here
switchMap(status => this.appService.updateShopSlotsStatus(status)),
tap(() => (this.changingStatus = false))
);
如果源(在这种情况下是changeSlotStatus$
可观测物)发射,switchMap
操作员将取消任何飞行中的可观测物。
我已经在Stackblitz中包含了exhaustMap
和mergeMap
的导入。将switchMap
更改为这两个操作符,看看它们的工作方式有何不同。exhaustMap
将忽略所有后续的发射,直到正在进行的发射完成,并且mergeMap
将发出与按下按钮一样多的请求。我将留给您来决定哪种方法是最好的!您可以在learn rxjs.上了解更多信息,我建议您阅读有关RxJS和不同运算符的内容,以及如何使用pipe
组合它们。RxJS是个好东西。
然后,如果您想要禁用正在运行的请求时按下的按钮,还可以绑定到changingStatus
布尔值。
https://stackoverflow.com/questions/67972014
复制相似问题