簡體   English   中英

如何在 Angular 中將 mergeWith 與主題一起使用

[英]How to use mergeWith with Subjects in Angular

目標:具有 3 個輸入的組合過濾器來過濾某些列表

限制:

  • 不應強迫用戶完成所有可用的過濾器來提交
  • 第一次提交應該在用戶輸入后發生
  • 一旦存在多個輸入,則組合不同的輸入

我的看法:我將輸入數據從 3 個不同的輸入組件發送到服務中的主題,該服務應充當輸入和實際組合之間的事件發射器,以便能夠根據需要重用和挑選不同的輸入

export class FilterInputStoreService {
  public selectedTypesHandler = new Subject<string>();
  public selectedPrivacyOptionsHandler = new Subject<boolean>();
  public searchInputHandler = new Subject<boolean>();
  constructor() {}
}

在過濾器組合組件中,我嘗試“監聽”主題是否發送了某些內容,並使用 mergeWith 將其與其余內容組合。

this.filterInputStore.selectedTypesHandler
    .mergeWith(this.filterInputStore.searchInputHandler, this.filterInputStore.selectedCurrenciesHandler )
    .map(() => {
       this.combinedDataObject = {
       Here i combine the values, doesnt matter for the question
        };
         }),
        tap(() => {
          this.filterService.newFilterData(this.combinedDataObject);
        })
       )
        .subscribe();

問題:

  • 它說 mergeWith 不能與 Subjects 一起使用
  • 其他運算符(例如 combineLatest)不起作用,因為它們需要等到每個源都有輸入。
  • 不能使用 Behaviorsubject,因為它會發出一個為 null 的初始值,導致過濾器崩潰

mergeWith ,像merge一樣可以與 Subjects 無縫協作。

例子 :

import { Subject } from 'rxjs';
import { mergeWith } from 'rxjs/operators';

const s1 = new Subject<string>();
const s2 = new Subject<string>();
const s3 = new Subject<string>();

s1.pipe(mergeWith(s2, s3)).subscribe(console.log);


s1.next('1')
s2.next('12')
s3.next('123')

// output 1, 12, 123. 

堆棧閃電戰

暫無
暫無

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

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