簡體   English   中英

RxJS篩選器/搜索主題,可觀察對象或BehaviorSubject

[英]RxJS Filter / Search Subject, Observable, or BehaviorSubject

我剛剛開始學習RxJS。 我沒有多大運氣就試圖做的一件事是,弄清楚如何搜索/過濾主題,或者創建一個可以觀察的數組。

我嘗試過管道傳遞和過濾Subject和BehaviorSubject,但是謂詞中的值是RxJS特定的。 根據我在各種文章上所讀的內容,方法是觀察數組以使用Subject。

我可以輕松地擁有兩個變量,一個數組和主題,然后搜索該數組。 但我想完成這一變量。

在淘汰賽中,可以搜索觀察到的數組。

RxJS有可能嗎?

提前致謝。

例:

layers: Rx.Subject<any> = new Rx.Subject<any>();

toggleLayer (layerId, visible) {

  //find layer we need to toggle

 // How do I search the subject to get the values added in next()?

   // tried from(this.layers), pipe does not fire
    const source = of(this.layers);

    const example = source.pipe(filter((val, index) => {
   //val is subject, and only iterates once, even if more than one value in subject
      // tslint:disable-next-line:no-debugger
      debugger;
      return false;
    }));

    const sub = example.subscribe((val) => {
      // tslint:disable-next-line:no-debugger
      debugger;
    });

}

private addLayer = (layerName, layerObj, layerType) => {

  // component class is subscribed to layers subject. Update UI when layer is added
  this.layers.next({
      layerId: this.layerId,
      name: `${layerName}_${this.layerId}`,
      layerObj: layerObj,
      visible: true,
      layerType: layerType
    });

}

我不清楚您要詢問的內容的100%,但是也許這個例子可以為您提供幫助。

const filterSubject = new BehaviorSubject<string>('b');
const dataSubject = new BehaviorSubject<string[]>(['foo', 'bar', 'baz', 'bat']);
const dataObservable = combineLatest(filterSubject, dataSubject).pipe(
  // given an array of values in the order the observables were presented
  map(([filterVal, data]) => data.filter(d => d.indexOf(filterVal) >= 0))
);

dataObservable.subscribe(arr => console.log(arr.join(',')));
// bar, baz, bat

使用combineLatest ,只要過濾器值或數據數組發生更改,就可以更新dataObservable值。

暫無
暫無

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

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