簡體   English   中英

清除一個可觀察數組 angular

[英]Clear a observable array angular

如何從可觀察數組中刪除所有項目? 它是無限卷軸的一部分

https://stackblitz.com/edit/infinite-scroll-firestore?file=app%2Fapp.component.html

 this.data = this._data.asObservable()
  .pipe(
    scan( (acc, val) => { 
      return this.query.prepend ? val.concat(acc) : acc.concat(val)
    })
  )

我想刪除數據數組中的所有內容。 重置函數對它只是從 _data 中刪除的可觀察數據沒有做任何事情

reset() {
  this._data.next([])
}

我也嘗試將其設置為 null 但它沒有用

reset() {
  this._data.next(null)
}

即使我這樣設置

this.data = new Observable 

下面的代碼會將空的可觀察數組分配給數據 object

this.data = of([]);

您可以應用幾個高階函數來改變 state:

const reset = () => (state) => [];
const add = (newValue) => (state) => [...state, newValue];
const overwrite = (newState) => (state) => newState;

const reset$ = new Subject();
const add$ = new Subject();
const data$ = this._data.asObservable()
...

const data = merge(
  reset$.pipe(map(reset)),
  add$.pipe(map(add)),
  data$.pipe(map(overwrite))
).pipe(
  scan((state, fn) => fn(state), [])
);
  • 接下來reset$將清除您的 state: reset$.next();
  • 將值添加到add$會將值添加到您的 state: add$.next(1);
  • 如果您的_data發出新值,它將覆蓋當前的 state

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM