确保最后一个 http post 在 Angular 中最后到达后端
Make sure that the last http post reaches back-end last in Angular
如何确保最后一个 http post 在 Angular 中最后到达后端?
我的用例。我有一个简单的由我实现的芯片列表。它由芯片和末尾的输入表示。当用户在输入中键入内容并按下 Enter
时,带有键入文本的筹码将添加到筹码列表中,用户也可以从列表中删除特定筹码。在添加和删除时,我都在后端更新芯片列表。这是负责此的代码。
addNewChip() {
if(this.chipText) {
this.chips.push(this.chipText);
this.chipText = "";
this.updateChipsOnBE();
}
}
removeChip(chipText) {
this.chips = this.chips.filter(text => text !== chipText);
this.updateChipsOnBE();
}
private updateChipsOnBE(): Observable<string[]> {
return this.chipAPI.update(this.BEAddress, this.chips);
}
现在我担心可能的竞争条件:this.chipAPI.update
操作可能尚未在 BE 上完成,而另一个 this.chipAPI.update
操作将以这种方式触发,使得后一个操作将在前者之前完成。这意味着,用户将丢失他或她应用的最后更改。
我感觉RxJS应该有办法阻止它,但我既找不到也想不出解决方案。
您需要在 chipAPI
中使用 concatMap
运算符。
类似于:
send$ = new Subject();
constructor(http: HttpClient) {
this.send$.pipe(
// contact waits until the inner stream has been completted.
concatMap(([address, chips]) => this.http.post(address, chips).pipe(
retry(5), // in case of failed request,
// catchError(() => EMPTY), // perhaps we can ignore errors
)),
// takeUntil(this.destroy$), // you need to implement an unsubscribe trigger.
).subscribe();
}
update(address, chips): {
this.send$.next([address, chips]);
}
如何确保最后一个 http post 在 Angular 中最后到达后端?
我的用例。我有一个简单的由我实现的芯片列表。它由芯片和末尾的输入表示。当用户在输入中键入内容并按下 Enter
时,带有键入文本的筹码将添加到筹码列表中,用户也可以从列表中删除特定筹码。在添加和删除时,我都在后端更新芯片列表。这是负责此的代码。
addNewChip() {
if(this.chipText) {
this.chips.push(this.chipText);
this.chipText = "";
this.updateChipsOnBE();
}
}
removeChip(chipText) {
this.chips = this.chips.filter(text => text !== chipText);
this.updateChipsOnBE();
}
private updateChipsOnBE(): Observable<string[]> {
return this.chipAPI.update(this.BEAddress, this.chips);
}
现在我担心可能的竞争条件:this.chipAPI.update
操作可能尚未在 BE 上完成,而另一个 this.chipAPI.update
操作将以这种方式触发,使得后一个操作将在前者之前完成。这意味着,用户将丢失他或她应用的最后更改。
我感觉RxJS应该有办法阻止它,但我既找不到也想不出解决方案。
您需要在 chipAPI
中使用 concatMap
运算符。
类似于:
send$ = new Subject();
constructor(http: HttpClient) {
this.send$.pipe(
// contact waits until the inner stream has been completted.
concatMap(([address, chips]) => this.http.post(address, chips).pipe(
retry(5), // in case of failed request,
// catchError(() => EMPTY), // perhaps we can ignore errors
)),
// takeUntil(this.destroy$), // you need to implement an unsubscribe trigger.
).subscribe();
}
update(address, chips): {
this.send$.next([address, chips]);
}