Tips for utilizing mergeWith with Subjects in an Angular application

Objective: Creating a Combined Filter with 3 Inputs to refine a list

Conditions:

  • Users are not required to complete all filters before submission
  • The first submit occurs when the user inputs data
  • Inputs are combined after more than one is provided

Approach: I transfer input data from the 3 different components to Subjects in a Service acting as an event emitter between input and combination. This allows for reusability and selection of various inputs as necessary.

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 "listen" for signals sent by subjects and merge them using mergeWith.

this.filterInputStore.selectedTypesHandler
    .mergeWith(this.filterInputStore.searchInputHandler, this.filterInputStore.selectedCurrenciesHandler )
    .map(() => {
       this.combinedDataObject = {
        Values are combined here, which is irrelevant for the question
        };
         }),
        tap(() => {
          this.filterService.newFilterData(this.combinedDataObject);
        })
       )
        .subscribe();

Issue:

  • An error states that mergeWith cannot be used with Subjects
  • Operators like combineLatest do not work as they require input from all sources
  • BehaviorSubject cannot be utilized because it emits a null initial value, leading to filter crashes

Answer №1

combineLatest is another operator that can be used in combination with Observables.

For instance :

import { Observable } from 'rxjs';
import { combineLatest } from 'rxjs/operators';

const obs1 = new Observable<number>();
const obs2 = new Observable<number>();
const obs3 = new Observable<number>();

obs1.pipe(combineLatest(obs2, obs3)).subscribe(console.log);


obs1.next(10)
obs2.next(20)
obs3.next(30)

// output 10, 20, 30.

Stackblitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty deploying a Node.js and Angular app on an Azure Web App via Azure DevOps

I am currently working on setting up a pipeline for my MEAN stack application in Azure DevOps. The frontend is developed using Node.js with Angular, while the backend is built with Node.js and Express. 1) Once I deploy the frontend Node.js project to an A ...

Nested validation schema featuring conditional validation - yes, we've got it covered!

In my Formik object, I have set initial values as follows: {customerDetails: {id: "", name: "", mobileNumber: ""}, notes: {id: "", text: "", type: ""}} How can I create a conditional Yup validati ...

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...

How can I exhibit JSON object information in an Angular 2 dropdown menu?

CSS <!-- Custom CSS Styling for Dropdown --> <div class="row no-overflow"> <div class="col-md-1 window-pad-height no-overflow"> <m ...

Issue with Socket.io: Data not received by the last user who connected

I have developed a Node.js and Express application with real-time drawing functionality on canvas using socket.io version 1.7.2. Users are divided into separate socket rooms to enable multiple teams to draw independently. However, there is an issue where t ...

Clarification Needed on Keyup Event in Angular 2

Within my application, I am dynamically adding a class based on certain conditions. When the user inputs something, I validate the value and then add the appropriate class accordingly. This functionality is functioning as expected. However, the class upda ...

Fullcalendar in Angular fails to update events automatically

I am exploring the integration of fullcalendar with angular. Despite adding valid events to my events field, they are not displaying in the UI. However, hardcoded events are appearing. I am relatively new to angular, so the issue may not be directly relat ...

Creating sophisticated TypeScript AngularJS directive

Recently, I came across a directive for selecting objects from checkboxes which can be found at this link: The issue I'm facing is that we are using TypeScript and I am unsure of how to implement the directive in TypeScript. From what I understand, ...

Karma's connection was lost due to a lack of communication within 10000 milliseconds

The Karma test suite is encountering issues with the following message: Disconnected, because no message in 10000 ms. The tests are not running properly. "@angular/core": "7.1.3", "jasmine-core": "3.3.0", "karma-jasmine": "1.1.2", The failure seems t ...

Is it possible to have routing only within child components in Angular 2?

I have set up a main component as the root component <tracker-module></tracker-module> Within the main component, there are sub-components structured like this: <header></header> <left-navigation></left-navigatio ...

Unexpected Union Type Return from Apollo Server

When I call my resolver to return a union type (either a User or an object with a message key and value of type String, such as my UserNotFoundError type), it always comes back with "__typename": "User". Why is this happening and how ca ...

Top Tips for Layering Components in Angular 5

Just starting out with Angular, currently in the process of creating a sample website. Created a cover page component named <app-coverpage> and have additional components that I want to overlap the cover page as part of the background effect. All c ...

Is there a way for me to operate the identical application in isolation?

I am looking to develop a unique service catering to individual companies. Instead of having the application run in the same container for each company, I would prefer to have a dedicated container for every company. For instance: google.serviceapplicat ...

Utilizing PrimeNG's p-dataView feature without repetitive FieldSets

Currently, I am utilizing p-dataView and I'm interested in implementing p-fieldset based on the application type. My goal is to prevent the fieldset from being duplicated when multiple instances occur. The scenario below illustrates one such case; how ...

What is the reason for the retrieval of jquery-3.5.1.min.js through the request.params.id expression?

For my school project, I am using Express.js with TypeScript to create a simple app. This router is used for the edit page of a contact list we are developing. It displays the ID of the current contact being edited in the search bar. The problem arises whe ...

Reimbursement for utilizing SwitchMap in Rxjs within the Angular framework

I'm new to using switchMap for the first time and I am encountering an issue. The console is asking me to return a value, but whenever I try to do so, it doesn't seem to be working properly. @Effect() subData$ = this.actions$.pipe( ofType( ...

Angular 2 integration for Oauth 2 popup authorization

I am in the process of updating an existing Angular application to utilize Angular 2. One challenge I am facing is opening an OAuth flow in a new pop-up window and then using window.postMessage to send a signal back to the Angular 2 app once the OAuth proc ...

Initializing ngOnInit and saving the value to an array variable

Currently, I am developing a function that retrieves data from an API. However, the function needs to be called within ngOnInit and the value should be stored in an array variable. MyValue: any; MyValue = MyLocation(); Unfortunately, the MyValue ends up ...

Steps to ensure that an API call is finished before proceeding with another task in Angular 2

Currently, I am utilizing angular 2 alongside ionic 2. The issue that I am facing is when I call an API, it does not return data immediately but starts another task instead. I need to ensure that the call completes entirely before proceeding to the next st ...