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

The Angular material Datepicker is encountering a conflict where multiple custom value accessors are trying to match a form control with an unspecified

Recently, I integrated a material datepicker widget into my Angular (7) application. The HTML code for this implementation is provided below. <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Expiry Date" [formControl]="expi ...

Angular - The element contains an implicit 'any' type due to the absence of an index signature in the 'AbstractControl' type

Within my Angular-11 project, I am utilizing the following TypeScript code: multistep = new FormGroup({ userDetails: new FormGroup({ first_name: new FormControl(''), last_name: new FormControl(''), other_na ...

Is Redux or Flux the default state management tool used in React?

After using npx create-react-app my-app --template typescript to create a new React app, what is the default software architecture (MVC, Redux, or Flux)? I've been researching the differences between them and it has left me feeling a bit confused. I w ...

ReactJS does not support merging multiple pages into one based on user button selection

My goal is to dynamically load a component based on the user's current page. List of Pages: Executables Shop In the main screen, there is a sidebar with two icons. The primary button should set the Executables Page and the second button should set ...

Sign up for an observable within an observable

Imagine a scenario where there is a function in a provider: saveCar(car: Car) { return this.saveCarImages(car).subscribe( (data:any) => { if(data[0].seats){ car=data[0]; } return this.api.put(`/car/${car.id}`, ca ...

Angular - Error: Unable to assign value to a reference or variable

I am currently working on an app built with Angular 8. app.component.html <div> <label class="form-check-label f-14"> <input type="checkbox" class="form-check-input" name="isAgree" [(ngModel)]="isAgree" #isAgree="ngModel"/> ...

Sharing API Results with All Components in Angular 7 using BehaviorSubject

My goal is to optimize an API call that fetches data about the current user (such as their username, full name, group memberships, email address, and more) by ensuring it's only made once per user session and that the data is shared across all compone ...

Struggling with module dependencies in Nest.js

I have been diving into the documentation provided on the NestJs website, but I've noticed that it can be a bit scattered. My goal is to retrieve an RPG Character from a Mongo database using TypeORM. Unfortunately, I seem to be running into dependency ...

Decompressing an array within a function invocation

Is there a method to pass an array's elements as arguments to a function? For instance, in Python I can accomplish this using: user = ["John", "Doe"] def full_name(first_name, last_name): return first_name + last_name Therefore, full_name(*user ...

Best Practices for Populating Input Fields with Data in ReactJS After Fetching Data

Currently, I am working on fetching data from an API and I could use some assistance on how to set the fetched date in input fields. It seems like a very basic issue for beginners, but any help will be greatly appreciated. Below is the code snippet: expor ...

Error message: The iOS system was unable to open the backing store due to a QuotaExceeded

Our Web-Application is quite large and is built on Angular with PWA capabilities enabled. Everything runs smoothly, including the offline mode functionality. We utilize PDFTron-Webviewer, which is cached by the Service-Worker to ensure availability in Off ...

Is there a way to both add a property and extend an interface or type simultaneously, without resorting to using ts-ignore or casting with "as"?

In my quest to enhance an HTMLElement, I am aiming to introduce a new property to it. type HTMLElementWeighted = HTMLElement & {weight : number} function convertElementToWeighted(element : HTMLElement, weight : number) : HTMLElementWeighted { elemen ...

Preselecting items in PrimeNG Checkbox: A step-by-step guide

How can I ensure that the already selected item is displayed upon loading this div? The code in `rp` consists of an array of type Permission with one element, which should be automatically selected. What could be causing the issue? Here is the HTML snippe ...

Exploring the process of retrieving two distinct values from a local JSON file

In my home page, I want to display categories and in the details page, I want to show menuItems. Currently, I am able to retrieve and parse categories in home.ts. How can I parse both categories and menu items in my typescript file, and fetch only menu ite ...

Setting a Validator for a custom form control in Angular: A step-by-step guide

I need to apply validators to a specific control in formGroup from outside of a custom control component: <form [formGroup]="fg"> <custom-control formControlName="custom"> </custom-control> </form> this. ...

The installation of Clarity through the command 'ng add @clr/angular' does not succeed

Following the guidance in 'Chapter 3: Building an Issue Tracking System using Reactive Forms' from Angular Projects: Discover Angular 12 with 10 innovative projects and cutting-edge technologies, 2nd Ed. by Aristeidis Bampakos. This chapter&apos ...

Creating a new function within the moment.js namespace in Typescript

I am attempting to enhance the functionality of the moment.js library by adding a new function that requires a moment() call within its body. Unfortunately, I am struggling to achieve this. Using the latest version of Typescript and moment.js, I have sear ...

Adjusting the width of a div element horizontally in Angular 4 and

As someone new to Angular 4, I've been attempting to create a resizable div (horizontally) without success. My goal is to be able to click and drag a grabber to resize the text area horizontally. However, in the example provided in the link below, the ...

Obtaining the date input value from the ng2-date-picker component in Angular2

I am struggling to extract the value from a date picker input field (ng2-date-picker). Despite attempting various methods to retrieve the value, I have not been successful. For reference, here is the link to the npm package I am utilizing. This represent ...

Prevent mat-table rows from collapsing when new data is added (Angular Material)

I'm currently in the process of creating an application that relies on real-time data updates every few seconds. The app utilizes a mat-table, which includes another mat-table within a collapsible row. While the collapsing functionality works properly ...