繁体   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