Is it possible to link observables in this manner? I've created a solution, but I'm uncertain if it's the most optimal approach

I have created a custom pipe in Angular to transform data retrieved from an observable using the async pipe. Here is the HTML code snippet:

<div class="meeting-dtls-sub-div" ***ngFor="let meeting of meetingData$ | async | hzCalendarFilter | async"**>
</div>

HzCalendarFilter.ts==

@Pipe({
  name: 'hzCalendarFilter',
})
export class HzCalendarFilterPipe implements PipeTransform {
  storedFilter$ = this.store$.pipe(select(getFilters));
  appliedFilterArr: string[] = [];
  constructor(private store$: Store<AppState>) {}
  transform(HzCaleDateArr: any = []) {
    return this.storedFilter$.pipe(
      map((filterArr: ICalendarFilter[]) => {
        this.appliedFilterArr = filterArr.filter((item) => item.isEnabled).map((data) => data.className);
        if (!!HzCaleDateArr) {
          return HzCaleDateArr.map((dateItem: any) => {
            return {
              ...dateItem,
              meetings: dateItem.meetings.filter((item: any) =>
                this.checkItemPresentOrNotAccordingToAppliedFilter(item.meetingType)
              ),
            };
          });
        }
      })
    );
  }
  checkItemPresentOrNotAccordingToAppliedFilter(meetingType: string) {
    const className = returnClassNameForMeeting(meetingType);
    if (!!className) {
      return this.appliedFilterArr.indexOf(className) > -1 ? true : false;
    }
  }
}

*I want to confirm if my approach of chaining async pipes like this (ngFor="let meeting of meetingData$ | async | hzCalendarFilter | async") is correct or not. Any feedback is appreciated.

Answer №1

The code is working fine, but I thought it might be helpful.

If you are using ngrx, you can simplify the code by using the select method directly on the store like this:

storedFilter$ = this.store$.select(getFilters);

to 

storedFilter$ = this.store$.select(getFilters)

Additionally, you can use pipes with Observables to avoid using async multiple times:

<div 
class="meeting-dtls-sub-div" 
*ngFor="let meeting of meetingData$ | hzCalendarFilter | async">

  ...

</div>

You can also write filters within the store pipe to filter out disabled items:

enabledStoredFilter$: Observable<string[]> = this.store$.select(getFilters).pipe(
    map((arr: ICalendarFilter[]) => {
      return arr.filter((x) => x.isEnabled);
    }),
    map((arr: ICalendarFilter[]) => arr.map((x) => x.className))
  );

Here is the complete code with the necessary imports and interfaces:

import { Pipe, PipeTransform } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';

// Define interfaces and functions here

@Pipe({
  name: 'hzCalendarFilter'
})
export class HzCalendarFilterPipe implements PipeTransform {
  // Add the logic for applying store filters and filtering date items here

}

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

Typescript: Implementing the 'types' property in a function returned from React.forwardRef

I'm exploring the option of adding extra properties to the return type of React's forwardRef function. Specifically, I want to include the types property. Although my current implementation is functional, given my limited experience with TypeScri ...

Tooltip implementation in Angular side bar is malfunctioning

I have integrated my angular 7 project side bar with a Tooltip from Angular Material, but I am facing issues with it not working properly. Can anyone guide me on how to correctly add the Tooltip functionality? Thank you. sidebar.component.html <ul cl ...

Is there a way to stop Material UI from dulling the color of my AppBar when using dark mode in my theme?

When I use mode: "dark" in my Material UI theme, it causes the color of my AppBar to become desaturated. Switching it to mode: "light" resolves this issue. This is how my theme is configured: const theme = createTheme({ palette: { ...

Deliver Compressed Files following Angular CLI --Prod Configuration

After using the Angular CLI's command to minify my basic Angular app, a dist folder was generated with the project folder and minified files. However, when I run ng serve, it always serves the unminified development files, whether it's in the roo ...

What is the correct way to start a typed Object in TypeScript/Angular?

As I delve into the world of Angular and TypeScript, I am faced with a dilemma regarding how to initialize an object before receiving data from an API request. Take for instance my model: //order.model.ts export class Order { constructor(public id: num ...

The issue arises when TypeScript declarations contain conflicting variables across multiple dependencies

My current project uses .NET Core and ReactJS. Recently, I updated some packages to incorporate a new component in a .tsx file. Specifically, the version of @material-ui/core was updated from "@material-ui/core": "^3.0.3" to "@material-ui/core": "^4.1.3" i ...

Utilize Typescript Functions to Interact with GeoJSON Data in Palantir Foundry

Working on a map application within Palantir utilizing the workshop module. My goal is to have transport routes showcased along roads depending on user inputs. I am familiar with displaying a route using GeoJSON data, but I'm wondering if there is a w ...

I am facing issues with testing a service in Angular that utilizes the HttpClient

Currently, I am working on an Angular 5 Project, but it's not a major project. However, I haven't been involved in the Angular2+ environment since early 2.1/2.2. My issue revolves around a Service that makes a call to a public API. Unfortunately ...

Tips for assigning the 'store_id' value to a variable in Angular 6 within the Ionic4 environment

Trying to retrieve the store_id from the StorageService in Ionic4 (angular 6). Managed to retrieve the store_id using: let id = this.storageService.get('store_id'); id.then(data => { this.store.push(data) }); After pushing it into an ar ...

Utilize Angular2 to dynamically add new routes based on an array register

Currently, I am utilizing Angular2 for the frontend of my project and I am faced with the task of registering new Routes from an array. Within my application, there is a service that retrieves data from a server. This data is then stored in a variable wit ...

Sort the list by the last name using Angular 2

Is there a way to arrange the contact list by LAST NAME, with names categorized under each alphabet? While I was able to achieve this in jQuery and Angular-1, I need guidance on how to implement this logic in Angular2/Ionic V2. ...

Using TypeScript to eliminate duplicate values when constructing an array with various properties

Recently, I received an array from an API that has the following structure: results = [ {name: 'Ana', country: 'US', language: 'EN'}, {name: 'Paul', country: 'UK', language: 'EN'}, {name: & ...

Problem with jasmine unit testing in a firebase-integrated ionic/angular application

I am currently working on an app using the Ionic and Firebase frameworks, and I have encountered an issue while writing unit tests for it. The error message I received is: Cannot read property 'subscribe' of undefined This error occurs during t ...

Accessing elements in a FormArray using formControl along with a personalized iteration

Currently, I have dynamic input fields that I want to incorporate into my form group. Here is the current setup: <div class="services" *ngFor="let section of sections"> <p> <mat-form-field> <mat-label&g ...

Troubleshooting issues with importing modules in TypeScript when implementing Redux reducers

Struggling to incorporate Redux with TypeScript and persist state data in local storage. My current code isn't saving the state properly, and as I am still new to TypeScript, I could really use some suggestions from experienced developers. Reducers i ...

Angular/Typescript code not functioning properly due to faulty expressions

What could be causing my {{ expression }} to malfunction? I have exhausted all options, yet the web browser fails to recognize this {{ expression }} or properly bind it using ng-bind. Instead, it either displays the {{ expression }} as is or not at all. C ...

Is it possible to visually distinguish the selected mat-grid-tile? Particularly when they are being created dynamically

On the user interface, I have a dynamic display of mat-grid-tile within a mat-grid-list. These tiles change in number and data based on backend values. When a user clicks on a mat-grid-tile, it triggers a function that receives the tile's data. My goa ...

Conditional application of Angular animations is possible

After implementing the fadein effect from Angular-Animations in my ASP.NET based Angular project, I encountered an issue where only the first row is faded-in while the other rows are not displayed when using *ngIf. Here is a snippet of the code: <ng-te ...

Is there a way to make a peer dependency optional in a project?

In the process of developing module A, I have implemented a feature where users can choose to inject a Winston logger into my module. As a result, winston becomes a peer dependency. However, when attempting to include module A in another module without th ...

What are the best practices for implementing jquery owlCarousel within an Angular 4 component?

I've included my 'carousel.js' file like this: $('#owl-carousel-1').owlCarousel({...}); and in carousel.component.html, I have: <div id="owl-carousel-1" class="owl-carousel owl-theme center-owl-nav home- carousel">....< ...