How can we leverage RxJS combineLatest for observable filtering?

I'm exploring the possibility of utilizing combineLatest in an Angular service to eliminate the need for the activeFiler$ switch block (The service should achieve the same functionality). Currently, this is the structure of the component design (stackblitz link), and I aim to retain only the render$ observable:

export class TodosComponent implements OnInit {
  constructor(private ts:TodoService) {}
  render$: Observable<Todo[]>; 
  activeFilter$: Observable<VISIBILITY_FILTER>;


ngOnInit() {
  this.render$ = this.ts.selectedTodos$;
  this.activeFilter$ = this.ts.activeFilter$;

  this.activeFilter$.subscribe(active=>{
        switch (active) {
    case VISIBILITY_FILTER.SHOW_COMPLETED:
      this.render$ = this.ts.completeTodos$;
      break;
    case VISIBILITY_FILTER.SHOW_ACTIVE:
      this.render$ = this.ts.incompleteTodos$;
      break;
    default:
      this.render$ = this.ts.todos$;
      }
  });
}
  }
}

As can be seen, I have set up this.render$ with an Observable obtained from the todo.service.ts file. The method is as follows:

  this.selectedTodos$ = 
  combineLatest(this.activeFilter$, this.completeTodos$, this.incompleteTodos$, this.todos$, this.applyFilter);

  private applyFilter(filter, completeTodos, incompleteTodos, todos): Todo[] {
    switch (filter) {
      case VISIBILITY_FILTER.SHOW_COMPLETED:
        return completeTodos;
      case VISIBILITY_FILTER.SHOW_ACTIVE:
        return incompleteTodos;
      default:
        return todos;
    }
  }

Given this setup, I believe I can do away with the

this.ts.ostore.observe(ACTIVE_FILTER_KEY).subscribe(active=>{
block in the todos component. However, upon removing it, the entire app stops functioning.

An interesting observation is that if I comment out the $activeFilter subscription and log this:

  this.render$ = this.ts.selectedTodos$;
  this.render$.subscribe(v=>console.log(v));

Although newly added todos are logged, they are not rendering. Any insights on this issue?

Answer №1

After troubleshooting, I finally got it to work successfully.

The key aspect that enables functionality is that combineLatest triggers when each individual Observable releases at least one value.

In my scenario, the ReplaySubject<Todo[]> objects were not notifying when the EStore was initialized. Consequently, the ReplaySubject<Todo[]>s were unable to activate the combineLatest operator.

To resolve this issue, I modified the implementation of the EStore so that it either emits no values or the entities with which the EStore was initialized. This adjustment proved to be effective in getting everything functioning smoothly.

   changeDetection: ChangeDetectionStrategy.OnPush

It now works seamlessly without the need for event emitters or @Input. Simply query the store and watch its magic unfold.

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

Angular 6 Universal does not pause for resolver completion

I recently completed the installation of Angular Universal start kit version 6 and designed my component within it. The main purpose of this component is to retrieve user information from an API upon loading and display it on the view. The issue I am faci ...

What is the best way to incorporate master/detail components without relying on hierarchical routes?

I need to combine the following elements. An index page with the route /items (plural). This page should be scrollable. When clicking on individual items, I want to display a detail page with the route /item/:id (singular). The detail page should have a ...

TypeScript requires that the `includes` function must have the same type parameter for both input and

When working with TypeScript, I've encountered an interesting dilemma regarding the use of the Array.Prototype.includes function. It seems that this function requires me to pass in the same type as in the original array, but isn't the purpose of ...

I am having trouble accessing the value from an Angular 2 service outside of the subscribe function

Within my component, there is a save function that looks like this: save() { var result; //For updating task if (this.task.AllTaskId) { if (this.task.AssignedToCode == null) { this.task.AssignedToCode = "All"; } ...

Creating a data type restricted to utilizing property names exclusively from a specified string union:

I have a specific Enum: enum MyEnum { optionOne = 0, optionTwo = 1, optionThree = 2, optionFour = 3, } and a related Type: export type EnumNamesList = keyof typeof MyEnum; I am looking to create a type similar to this: export type EnumDataTypes = ...

Transferring an Image from Angular 7 to Spring-boot

I've been attempting to transfer images from my Angular application to Spring Boot, but I'm encountering issues. When I send a POST request from Angular with the file, Spring Boot doesn't respond as expected. To investigate further, I tested ...

What is the best way to determine the appropriate generic type for this situation?

Here is an example of some code: type secondaryObjectConstraint = { [key: string]: number } abstract class Base<TObject extends object, TSecondaryObject extends secondaryObjectConstraint> {} type secondaryObjectType = { myProp: number } c ...

Deactivate the react/jsx-no-bind warning about not using arrow functions in JSX props

When working with TypeScript in *.tsx files, I keep encountering the following error message: warning JSX props should not use arrow functions react/jsx-no-bind What can I do to resolve this issue? I attempted to add configurations in tslint.json js ...

Turf.js - Missing type declarations when importing into a Vue/Vite environment

Struggling with Turf.js's bbox functionality. Despite all my efforts, TypeScript type definitions remain elusive. I attempted the following steps: Included in package.json: "dependencies": { ... "@turf/turf": "6.5.0&q ...

What is the reason for requiring that the value type in a map must be uniform?

When using TypeScript, I expect the map type to be either a number or string, but unfortunately, an error is being reported. Click here for the Playground const map: Map<string, string | number> = new Map([ [ '1', &apo ...

Http service not found

I am facing a problem with injecting HTTP into my Angular 2 application. Everything was working smoothly a few days ago, but now I am encountering this error: ORIGINAL EXCEPTION: No provider for Http! Here is the code snippet from main.ts: import { pl ...

Updating Error: Unable to establish connection with IP address 104.16.21.35 on port 80; Error code: ECONNREFUSED. This issue is being handled by the _

I need help updating my Angular version from 5 to 6 and I'm following these steps: Want to upgrade project from Angular v5 to Angular v6 After running the commands ng update @angular/cli and ng update @angular/core, I encountered the err ...

What could be causing a custom Angular library to fail to compile after being published on npm?

I recently launched a library that I created for my team to expedite the process of developing applications specifically for the Internet of Things (IOT) sector. However, I have encountered an issue where the library compiles without errors in the demo pro ...

When trying to reference a vanilla JavaScript file in TypeScript, encountering the issue of the file not being recognized

I have been attempting to import a file into TypeScript that resembles a typical js file intended for use in a script tag. Despite my efforts, I have not found success with various methods. // global.d.ts declare module 'myfile.js' Within the re ...

Setting the background color of a button within a template in an Angular 8 component using style.background

I have been exploring the different versions of Angular and their changes. Currently, I am enrolled in an Angular course on Udemy where I have installed Angular 8. In the course, it is mentioned to use style.backgroundColor on a button inside the template ...

Is it possible to specify the version of a dependency using Stackblitz?

Is it possible to specify the dependency version on StackBlitz? I recently updated the dependency on NPM, however StackBlitz seems to be stuck on installing the old version. ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

Custom typings for Next-Auth profile

I'm experiencing an issue with TypeScript and Next Auth type definitions. I followed the documentation guidelines to add my custom types to the NextAuth modules, specifically for the Profile interface in the next-auth.d.ts file. It successfully adds t ...

Incorporating Precision to Decimal Numbers in TypeScript Angular

Having some trouble with this issue and I've tried various solutions without success. This problem is occurring within an Angular project. The requirement is to always display a percentage number with two decimal places, even if the user inputs a who ...

Errors encountered when using TypeScript with destructured variables and props not being recognized

I have a function that returns data. The object is structured with properties such as headerMenu, page, content, and footer. These properties are defined in DataProps interface. When I try to destructure the data object using the line: const { headerMenu, ...