因此,假設我從后端檢索條目并將其顯示在表格中。現在,用戶想要通過單擊按鈕來洗掉條目。
該條目必須在服務器端洗掉,并且 ui 應反映更改。我不想從后端重新加載所有條目,而是從模型中洗掉已洗掉的條目,基于該模型呈現表(entries$)。
我嘗試了以下方法:
deleteEntrySubject = new BehaviorSubject<any>(null);
deletedEntry$ = this.deleteEntrySubject.asObservable();
//.pipe(switchMap(e => this.entryService.delete(e)));
entries$ = combineLatest([
of([
{ n: '1', id: 1 },
{ n: '2', id: 2 },
]),
this.deletedEntry$,
]).pipe(
filter(([entries, deletedEntry]) => deletedEntry !== null),
map(([entries, deletedEntry]) =>
entries.filter((entry) => entry.id !== deletedEntry?.id)
)
)
.subscribe((result) => console.log('res', result));
deleteEntry(id) {
this.deleteEntrySubject.next({ n: id, id: id });
}
效果很好 - 但是由于初始的 observable(這里由 提供of())沒有改變,它每次都會以相同的兩個值開始。因此,當洗掉條目 1 時,我將在結果中包含條目 2,然后當我洗掉條目 2 時,我將在結果中獲得條目 1(它不應再出現,因為它之前已被洗掉。
我知道 Observables 不能“改變”——但同時我不知道如何以 rxjs 的方式實作這一點,而不必使用某些組件狀態來記住哪些條目已被洗掉。
那么這里的動作是什么?我如何使它“正確”?
上面的代碼可以在這里找到:https ://stackblitz.com/edit/angular-ivy-dibess?file=src/app/hello.component.ts
uj5u.com熱心網友回復:
您可以將從服務器接收到的資料存盤entries$ = new BehaviorSubject<any[]>([])在組件內的本地存盤 ( ) 中(理想情況下,這應該存盤在服務/存盤...等而不是組件中)。然后,您可以在每次要從中洗掉或更新此存盤時更新/發出該存盤的源,如下所示:
entries$ = new BehaviorSubject<any[]>([]);
get entries() {
return this.entries$.value;
}
ngOnInit() {
this.fetchData();
}
fetchData() {
this._mockHttpGet().subscribe((res) => this.entries$.next(res));
}
deleteEntry(id) {
const newEntries = this.entries.filter((item) => item.id !== id);
this.entries$.next(newEntries);
}
/** Mock of you HTTP request */
private _mockHttpGet(): Observable<any[]> {
return of([
{ n: '1', id: 1 },
{ n: '2', id: 2 },
]);
}
這是一個具有所需更改的有效StackBlitz版本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/510215.html
標籤:有角度的rxjs
上一篇:RxJSfrom()和陣列
下一篇:預期2-3個引數,但得到1.ts(2554)index.d.ts(2559,23):Anargumentfor'body'isnotprovided
