Executing a function in Angular depending on the values emitted by two distinct observables

As someone who is relatively new to Angular (6 months), I am facing a challenge with my code. Currently, I have two observables that are working independently of each other:

this.siteService.siteChanged$
  .pipe(takeUntil(this.disconnect$))
  .subscribe(_ => this.getGroups());

this.uiService.currentTab$
  .pipe(takeUntil(this.disconnect$))
  .subscribe(tab => {
    if (tab != Tab.Groups) {
      this.windowService.pushToHistory({ group: this.groupService.selectedGroup?.groupId }, true);
    }
    else {
      this.totalCountChange.emit(this.allGroups.length);
      this.filteredCountChange.emit(this.filteredGroups.length);
    }
  });

The issue I am encountering is that the method "this.getGroups()" from the first observable needs to be called only when the "tab" returned in the second observable is equal to "Tab.Groups". However, I am struggling to find a way to combine them efficiently. I attempted using "forkJoin", but I couldn't successfully retrieve the value of "tab" when the first one returns void, resulting in errors:

forkJoin(
  [this.siteService.siteChanged$,
  this.uiService.currentTab$]
).subscribe([void,tab] => {
  if(tab == Tab.Groups){
    this.getGroups();
  }
})

Answer №1

After some experimentation, I have implemented the following solution that appears to be functioning correctly. However, I am open to suggestions for a better or more efficient approach. Please feel free to contribute your insights.

  this.siteService.siteChanged$.pipe(takeUntil(this.disconnect$)).subscribe(() => {
  this.uiService.currentTab$.pipe(takeUntil(this.disconnect$)).subscribe(tab => {
    if (tab == Tab.Groups) {
      this.getGroups();
      this.totalCountChange.emit(this.allGroups.length);
      this.filteredCountChange.emit(this.filteredGroups.length);
    }
    else {
      this.windowService.pushToHistory({ group: this.groupService.selectedGroup?.groupId }, true);
    }
  })
});

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 trouble installing Angular Material due to a getaddrinfo ENOTFOUND error?

When attempting to execute ng add @angular/material in my Angular project, I encountered the following error: Unable to fetch package metadata: request to http://registry.npmjs.org/@angular%2fmaterial failed, reason: getaddrinfo ENOTFOUND proxy.{companyna ...

Troubleshooting the issue with the HTTPClient get method error resolution

Currently, I am attempting to capture errors in the HTTP get request within my service file. Below is the code snippet: import { Injectable } from '@angular/core'; import { PortfolioEpicModel, PortfolioUpdateStatus } from '../models/portfol ...

Adding an item to an array in Angular 2 using JavaScript!

In my Angular2 form, I have a field that consists of an array of objects. I've successfully created a table with a Delete Row button for each row and an Add Row button using the push() and slice() methods in JavaScript. However, there's a major ...

Encountered difficulties in deploying functions on Firebase Cloud Functions

While developing the Firebase Cloud Functions, I organized the files based on each function. Unfortunately, numerous errors occurred during deployment. Error [debug] [2022-07-19T14:36:17.677Z] <<< [apiv2][body] GET https://us.gcr.io/v2/xxxxxx/gcf ...

Error encountered: The input value does not correspond to any valid input type for the specified field in Prisma -Seed

When trying to run the seed command tsx prisma/seed.ts, it failed to create a post and returned an error. → 6 await prisma.habit.create( Validation failed for the query: Unable to match input value to any allowed input type for the field. Parse erro ...

Building an Angular 4 universal application using @angular/cli and integrating third-party libraries/components for compilation

While attempting to incorporate server side rendering using angular universal, I referenced a post on implementing an angular-4-universal-app-with-angular-cli and also looked at the cli-universal-demo project. However, I ran into the following issue: Upon ...

Guide to customizing CSS styles within a div element using TypeScript code in a Leaflet legend

I'm struggling to add a legend to my map using Angular 5 and typescript. I need help with setting CSS styles for the values (grades) that are displayed on the legend. Can someone guide me on where to put the styles? TS: createLegend() { let lege ...

What are the steps for implementing the Ionic 2 Pulling Refresher feature in my application?

Hey everyone, I'm currently working on developing a mobile app using AngularJS 2/Ionic2. I am facing an issue with implementing a pull-to-refresh feature in my app. We followed the steps outlined in this link, and while we were able to get the page to ...

Sharing information between components in Angular through service communication

In my Angular 4 project, there is a functionality where upon clicking on one of the 'groups', its tile should be added to a list of 'favourites' which is represented as an array. To implement this feature, I utilized a BehaviorSubject. ...

Reactify TypeScript: Accurate typings for onChange event

How can I resolve the issues with types for target: { value: any, name: any }? The errors I encounter include Duplicate identifier 'any'. and Binding element 'any' implicitly has an 'any' type.. Additionally, why does the erro ...

Typescript error: RequestInit not properly initialized

I'm encountering an issue while using fetch to call an API in a typescript file. The browser is throwing an error stating that const configInit must be initialized, even though I believe it is already. Any suggestions on how to resolve this? Thank you ...

Including a hyperlink in a table using Angular 8

I have a table with multiple columns, one of which is the "documents" column that contains downloadable files. How can I make just the document name clickable as a link? HTML <p-table #dt3 [columns]="colsPermessi" [value]="permessi" [paginator]="true" ...

Tips for eliminating inline CSS usage in React

Is it possible to avoid using inline CSS in React when styling an element like this? const dimensionStyles = { width: 10, height: 20 }; <div className="point-class" style={{ width: dimensionStyles.width + "px", height: ...

Fetching values from JSON object using Key in Angular

Here is the code snippet for the markup and component in question: new.component.html <a routerLink="{{sub.name}}" routerLinkActive="active">{{sub.name}}</a> old.component.ts data; this.route.params.subscribe((params:any) => {console.lo ...

Mastering the use of Action.Submit in adaptive cards to simulate user input

I am trying to implement MessageFactory.SuggestedActions within my "welcomeCard" adaptive card. Essentially, in my adaptive card (welcome card), I have several buttons for the user to click on, each with an Action.Submit type. { "type" ...

Align the running of Angular code with a for loop

I am currently working on a project with Angular 9 and Spring Boot as the backend. The nature of the project is CMS based, where users can create forms using reactive form technology. These forms have the capability to include multiple file upload fields. ...

Converting an object within an object into an Angular Class (Type)

Is there a way to convert the value of obj.category into the Category type as shown in the example below? I specifically need this conversion in order to select options in a dropdown. export class Category{ id: number; name: string; construc ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

"Jest test.each is throwing errors due to improper data types

Currently, I am utilizing Jest#test.each to execute some unit tests. Below is the code snippet: const invalidTestCases = [ [null, TypeError], [undefined, TypeError], [false, TypeError], [true, TypeError], ]; describe('normalizeNames', ...

Utilizing Typescript template strings for data inference

In coding practice, a specific convention involves denoting the child of an entity (meaning an association with another entity) with a '$' symbol. class Pet { owner$: any; } When making a reference to an entity child, users should have the opt ...