Exploring the potential of the forkJoin operator in Angular 4's Observable

I'm currently facing a challenge that involves retrieving both administrators and professionals from the "users" collection using AngularFire's latest version. I am utilizing Observables for this task.

My goal is to make two parallel requests and combine the results of administrator and professional users into one response. I attempted to achieve this using the forkJoin operator as shown below:

 getUsers(): Observable<any> {
  return forkJoin([
    this.afs.collection('users', ref => ref.where('roles.admin', '==', true)).valueChanges(),
    this.afs.collection('users', ref => ref.where('roles.professional', '==', true)).valueChanges()
  ])
  .map((data: any) => {
    console.log(data)
    return data;
  });

}

However, upon calling the method like this:

this.userSrv.getUsers()
.subscribe((res) => {
  console.log(res);
});

I encountered an issue where it didn't execute as expected. Here are my imports:

import {Observable} from 'rxjs/Rx';
import { forkJoin } from 'rxjs/observable/forkJoin';
import 'rxjs/add/operator/map';

If you have alternative solutions or suggestions on how to tackle this problem, your guidance would be greatly appreciated. Thank you.

Answer №1

It seems like the issue lies in the fact that .valueChanges() returns a ‘hot’ observable, which does not complete. According to the forkjoin documentation:

Wait for Observables to complete and then combine last values they emitted.

It appears that what you need is likely .combineLatest():

getUsers(): Observable<any> {
  return Observable.combineLatest(
    this.afs.collection('users', ref => ref.where('roles.admin', '==', true)).valueChanges(),
    this.afs.collection('users', ref => ref.where('roles.professional', '==', true)).valueChanges()
  )
  .map((data: any) => {
    console.log(data)
    return data;
  });
}

This function should output an array containing two items representing the two collections whenever either of them are updated.

Answer №2

Consider using this code snippet:

const request1 = this.http.get('https://request1');
const request2 = this.http.get('http://request2');

forkJoin([request1, request2]).subscribe(data => {
  // data[0] contains response from request1
  // data[1] contains response from request2
  this.request1Response = data[0];
  this.request2Response = data[1];
});

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 with installing Typescript on a MacBook?

I have been attempting to follow the instructions provided on TypeScriptLang.org but for some reason, I am unable to successfully download typescript. This is what I have tried so far: mkotsollariss-MacBook-Pro:/ mkotsollaris$ which node /usr/local/bin/n ...

Issues persist with the implementation of async in Angular2+

In my Angular2+ component, I created a function that outputs the results before actually running the function. This causes the desired output to appear later than expected. The function sends a variable parameter with an HTTP request to a NodeJS backend an ...

Troubleshooting issue with absolute paths in Vite project using React and TypeScript

I'm having trouble implementing absolute paths in a Vite react-ts project. This is how I set up the project: npm init @vitejs/app npx: installed 6 in 1.883s √ Project name: ... test-vite √ Select a framework: » react √ Select a variant: » rea ...

Substitute all attributes of objects with a different designation

I need to update all object properties from label to text. Given: [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", &q ...

Tidying up following the execution of an asynchronous function in useEffect

Recently, I've been facing a challenge while migrating a React project to TypeScript. Specifically, I'm having trouble with typing out a particular function and its corresponding useEffect. My understanding is that the registerListener function s ...

Tips for accurately implementing the onHoverIn TS type in the React Native Web Pressable component

I'm working with React Native Web and Typescript, and I want to integrate the React Native Web Pressable component into my project. However, I encountered an issue where VSCode is showing errors for React Native Web prop types like onHoverIn. The pro ...

Flow - secure actions to ensure type safety

Currently implementing flow and looking to enhance the type safety of my reducers. I stumbled upon a helpful comment proposing a solution that seems compatible with my existing codebase: https://github.com/reduxjs/redux/issues/992#issuecomment-191152574 I ...

What is the best way to incorporate ng-select within a custom form controller?

I've attempted to create a stackblitz demo to illustrate my issue, but unfortunately, I couldn't make it work properly. Therefore, I'm reaching out for assistance. I have 2 components: Component 1 is a specialized form controller that encap ...

Is there a way to delegate properties in Angular 2+ similar to React?

When working with React, I have found it convenient to pass props down dynamically using the spread operator: function SomeComponent(props) { const {takeOutProp, ...restOfProps} = props; return <div {...restOfProps}/>; } Now, I am curious how I ...

Oops! NG0900 error occurred while attempting to differentiate '[object Object]'. Please note that only arrays and iterables are permissible, so please stick to using observables and subscribe methods

Struggling to fetch data from an API and pass it to a component for use in a table, but encountering the same issue repeatedly. The data is visible, yet there seems to be a glitch. Here's a snippet from my console: enter image description here Snipp ...

Is it necessary for TypeScript classes that are intended for use by other classes to be explicitly exported and imported?

Is it necessary to explicitly export and import all classes intended for use by other classes? After upgrading my project from Angular 8 to Angular 10, I encountered errors that were not present before. These issues may be attributed to poor design or a m ...

The functionality to subscribe in ts(6385) has been marked as

I am encountering an error message regarding the deprecation of the subscribe function in my code. The issue seems to be with the second part of the code for the getStarwarsHeroes function, where the .subscribe method is being deprecated. import { Injectab ...

Is it possible to combine two separate host listeners into a single function in Angular 2?

One solution is to combine 2 different host listeners into a single function so that it can be called whenever needed. @HostListener('window:unload', ['$event']) unloadHandler() { this.eventService.send({ name: 'onUnload' }) ...

Subject.next() not triggering Observable on value change

I'm currently working on developing an autocomplete feature using Observable and Subject in Angular. However, I've run into an issue where the service method is not triggered when the Subject object's value changes. Below is a snippet of my ...

Getting permission for geoLocation service on iOS in Ionic: A step-by-step guide

I have recently developed a social media application that utilizes geoLocation services. The app is built with Ionic 4 and has a Firebase backend. While the GeoLocation services are functioning properly on Android devices, users of iOS are not being prompt ...

Automatically log into Google using Angular with Angularx-Social-Login

Utilizing Google sign-in and Angularx-Social-Login to authenticate users has been successful for me. However, I am facing an issue where users have to log in again whenever they reload the page or open a new tab, despite setting autologin: true. I have imp ...

Displaying text and concealing image when hovering over a column in an angular2 table

I am currently using a table to showcase a series of items for my data. Each data entry includes an action column with images. I would like to implement a feature where hovering over an image hides the image and reveals text, and vice versa (showing the im ...

What is the method to obtain the complete URL in Angular?

I'm exploring ways to utilize Angular Universal in my app and I am seeking a method to retrieve the complete path of the current url within an Angular component. Initially, I considered tapping into the window object which would involve injecting it o ...

Tips for making a property non-nullable in Typescript

The Node built-in IncomingMessage type from DefinitelyTyped's definition (used as req in the (req, res, next) arguments) has specified that url can be nullable. This excerpt shows part of the definition: // @types/node/index.d.ts declare module "http ...

exit out of React Dialog using a button

I have a scenario where I want to automatically open a dialog when the screen is visited, so I set the default state to true. To close the dialog, I created a custom button that, when clicked, should change the state to false. However, the dialog does no ...