简体   繁体   English

如何在 Angular 中将 mergeWith 与主题一起使用

[英]How to use mergeWith with Subjects in Angular

Goal: A Combined Filter with 3 Inputs to filter some list目标:具有 3 个输入的组合过滤器来过滤某些列表

Restrictions:限制:

  • The User should not be forced to complete all available filters to submit不应强迫用户完成所有可用的过滤器来提交
  • The first submit should happen once the user inputs第一次提交应该在用户输入后发生
  • Different Inputs are combined once there is more than one一旦存在多个输入,则组合不同的输入

My Take: I send the input data from the 3 different input components to Subjects in a Service that should act as event emitter between input and the actual combination, to be able to reuse and cherry pick different inputs as needed我的看法:我将输入数据从 3 个不同的输入组件发送到服务中的主题,该服务应充当输入和实际组合之间的事件发射器,以便能够根据需要重用和挑选不同的输入

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

In the filter combination component i try to "listen" to if a subject sends something and combine it with the rest using mergeWith.在过滤器组合组件中,我尝试“监听”主题是否发送了某些内容,并使用 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();

Problem:问题:

  • It Says mergeWith cannot be used with Subjects它说 mergeWith 不能与 Subjects 一起使用
  • Other operators like combineLatest dont work because they require to wait until every of the sources has an input.其他运算符(例如 combineLatest)不起作用,因为它们需要等到每个源都有输入。
  • Cant use Behaviorsubject because that emits an initial value which is null, causing the filter to crash不能使用 Behaviorsubject,因为它会发出一个为 null 的初始值,导致过滤器崩溃

mergeWith , like merge works seamlessly with Subjects. mergeWith ,像merge一样可以与 Subjects 无缝协作。

Example :例子 :

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. 

Stackblitz堆栈闪电战

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM