combineLatest will trigger only for the initial event

I am looking to combine 3 events and trigger a service call when any of them are fired. Currently, I am using the combineLatest method, but it seems to only work when the first event is triggered by filterChanged.

The issue here is that filterChanged is a local event, while the other two events come from a child component. How can I modify this setup so that even if one of the events is emitted during page initialization, it will still trigger the service?

filterChanged = new EventEmitter<boolean>();
paginatorChanged = new EventEmitter<MatPaginator>();
sortChanged = new EventEmitter<{}>();

ngAfterViewInit(): void {
   combineLatest(
      this.paginatorChanged,
      this.sortChanged,
      this.filterChanged
   ).pipe(
      startWith([null, null, null]),
      switchMap(value => {
      const paginator = value[0];
      const sort = value[1];
      const filters = value[2];
    
      return this.service.getFiltered(paginator, sort, filters);
   })).subscribe(data => this.data = data);
}    

applyFilter(): void {
  this.filterChanged.emit(true);
}

onPaginatorChanged(paginator): void {
  this.paginatorChanged.emit(paginator);
}

onSortChanged(sort): void {
  this.sortChanged.emit(sort);
}

Thank you!

Answer №1

Currently, the question lacks clarity. However, if you aim to initiate the combineLatest functionality 'without' the filterChanged observable emitting at least once, it seems that the issue lies in incorrectly using the startWith operator. It should be applied to each source observable individually.

Consider the following approach:

ngAfterViewInit(): void {
  combineLatest(
    this.paginatorChanged.pipe(startWith(null)),
    this.sortChanged.pipe(startWith(null)),
    this.filterChanged.pipe(startWith(null))
  ).pipe(
    switchMap(value => {
    const paginator = value[0];
    const sort = value[1];
    const filters = value[2];
  
    return this.service.getFiltered(paginator, sort, filters);
    })
  ).subscribe(data => this.data = data);
}

Furthermore, for local multicast observables, consider utilizing RxJS Subject (or its counterparts) instead of relying on Angular-specific EventEmitter.

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

Tips for adding npm modules in StackBlitz?

Is it possible to install npm packages for Angular on StackBlitz without a terminal? I'd like to know the process. ...

How can we make type assertions consistent without sacrificing brevity?

In the project I am currently working on, we have implemented a warning for typescript-eslint/consistent-type-assertions with specific options set to { assertionStyle: 'as', objectLiteralTypeAssertions: 'never' }. While I generally appr ...

Embedding content within various ng-template elements

I'm currently working on developing a button component (app-button) that can utilize multiple templates based on the parent component using it. <div class="ds-u-margin-left--1 ds-u-float--left"> <ng-container *ngTemplateOutlet="icon">< ...

Learn the process of inserting a table in ExcelJS specifically for Angular applications

I encountered an issue when attempting to add a table with data. An error message stating "AddTable is not function" appeared. let workbook = new ExcelJS.Workbook(); let worksheet = workbook.addWorksheet("Data"); worksheet.addTable({ name: 'My ...

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

How to simulate a typescript class using vitest

I am encountering a situation where I have a class A that imports another class B from a separate module and creates an instance of it. While writing tests for class A, I want to stub or mock some of the methods of class B. Below is an example code snippe ...

A long error occurred while using the payloadaction feature of the Redux Toolkit

import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit" import axios, { AxiosError} from "axios" type user = { id: number, token: string } export type error = { error: string } interface authState { user: user | ...

unable to reinstall due to removal of global typing

After globally installing Moment typing with the command typings install dt~moment --save --global Checking the installed typings using typings list shows: ├── <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93fffcf7f2e0 ...

The issue arises when attempting to use the search feature in Ionic because friend.toLowerCase is not a valid function

I keep encountering an error message that says "friend.toLowerCase" is not a function when I use Ionic's search function. The unique aspect of my program is that instead of just a list of JSON items, I have a list with 5 properties per item, such as f ...

Leverage the power of RXJS to combine the results from two observables

I want to extract parameters from the URL and use those values to trigger an observable. Once a result is returned, I would like to proceed with that and initiate another observable call. My goal is to wrap both calls so I only need to subscribe once to re ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

Initial value not being recognized by mat-input attribute disable

My current challenge involves toggling the enable/disable status of mat-inputs based on a specific property value within an object. Within my component, I am subscribing to an observable in my service that retrieves applications with a default disabled fl ...

Can a generic type be utilized to instantiate an object?

In my code, I have a class named Entity as shown below: class Entity { constructor(readonly someValue: string) {} someFunction() {} } Now, I am trying to create a class that will handle these entities and be able to create instances of them. In or ...

Typescript type/object's conditional property feature

Imagine having a recipe ingredient type structured like this export type RecipeIngredient = { name: string; amount: Number | string; unit: "grams" | "milliliters" | "custom"; }; To illustrate const apples: RecipeIngredient = { name: 'apples&a ...

Tips on typing the onFocus function event parameter for a Material UI Input component

Currently, I am working on a custom dropdown using material ui components like Input and Popper. The goal is to have the popper open when the user focuses on the input field. Additionally, I am implementing this solution with TypeScript. import ClickAwayL ...

The most suitable TypeScript type for a screen being utilized again in react-navigation v5

When it comes to typing screens under react-navigation v5, I usually follow a simple pattern: // Params definition type RouteParamsList = { Screen1: { paramA: number } Screen2: undefined } // Screen1 type Props = StackScreenProps<R ...

Tips for testing the window.innerWidth property in Angular 8?

I am relatively new to Angular and TDD. Right now, I am attempting to test a function that is called during a resize event. Below is the code snippet in question: header.component.ts @Component({ selector: 'app-header', templateUrl: &ap ...

Increasing a number after a delay in an Angular 2 AppComponent using TypeScript

I'm attempting to create a straightforward Angular2 Application with TypeScript. Despite its apparent simplicity, I'm struggling to achieve my desired outcome. My goal is to display a property value in the template and then update it after 1 sec ...

Hiding the line connector between data points in ChartJs

I recently took over a project that includes a line chart created using Chart.js by the previous developer. My client has requested that I do not display a line between the last two data points. Is this possible with Chart.js? I have looked through the doc ...

Adding a constant to a Vue component

Currently working on developing an application using Vue and TypeScript. I'm focused on refactoring some aspects, particularly moving hard-coded strings from a template to a separate constant. What has been implemented is as follows: export const va ...