Combine two arrays of data sources

mergeThreads() {
    const userId = this.auth.getUser().uid;
    const buyerThreads$ = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges();
    const sellerThreads$ = this.afs.collection('threads', ref => ref.where('sellerId', '==', userId)).valueChanges();
    
    this.subscription = forkJoin(buyerThreads$, sellerThreads$)
      .pipe(
        map(([bT, sT]) => [...bT, ...sT])
      )
      .subscribe(res => { 
        console.log(res); // output not displaying
        // logic to check for unread threads should be implemented here
      });
}

In order to ascertain real-time updates regarding unread messages in my Firestore database's 'threads' collection, I have chosen to use AngularFire2 and its querying capabilities. Due to the limitations of AngularFire2 where querying with multiple conditions might yield unexpected results, I had to think of a different approach. My goal is to combine two Observable arrays into a single array to provide timely notifications to users concerning their message status.

After trying out a code snippet (borrowed from an answer on Stack Overflow), I realized that nothing was being outputted in the subscribe method. This led me to believe that perhaps my observables continue streaming without completing, hampering the subscription process. Is there a way to effectively merge two ongoing observable streams into one dynamic array, or do I need to consider an alternative strategy?

Answer №1

Instead of using forkJoin, try implementing combineLatest.

Here is the updated approach...

checkAllThreads() {
    const userId = this.auth.getUser().uid;
    const buyerThreads = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges();
    const sellerThreads = this.afs.collection('threads', ref => ref.where('sellerId', '==', userId)).valueChanges();
    this.subscription = Observable.combineLatest(buyerThreads, sellerThreads)
      .map(([bT, sT]) => [...bT, ...sT])
      .subscribe(res=> { 
        console.log(res);
      });
  }

You may have to include these imports.

import 'rxjs/add/observable/combineLatest';
import { Observable } from 'rxjs/Observable';

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

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...

"Unsuccessful API request leads to empty ngFor loop due to ngIf condition not being

I have been struggling to display the fetched data in my Angular 6 project. I have tried using ngIf and ngFor but nothing seems to work. My goal is to show data from movies on the HTML page, but for some reason, the data appears to be empty. Despite tryin ...

What could be causing the error message (No overload matches this call) to pop up when attempting to subscribe to .valueChanges() in order to retrieve data from Firestore?

Currently, I am developing an Angular application that utilizes Firebase Firestore database through the angularfire2 library. However, I am encountering a challenge. I must admit that my background is more in Java than TypeScript, so there might be some g ...

Retrieve select options only upon clicking

Essentially, I have a default value that needs to be loaded into a select element and then make an API call to load the rest only when the select is clicked. <select (click)="getSubevents(market_uri)"> <option *ngFor="let subeven ...

Navigating to a different page in Ionic 2 when a link or button is clicked

When I click on the link provided below, it should take me to the home page. However, I am facing issues and it is not redirecting me as expected. I want to be taken to the home page when clicking on the specified link or button. Do I need to add any Ang ...

Testing units in Angular using different sets of test data

When it comes to unit testing a C# method with different sets of data, the Theory and InlineData attributes can be used to pass multiple inputs for testing purposes. [Theory] [InlineData("88X", "1234", "1234", "1234")] [InlineData("888", "123X", "1234", " ...

Asynchronous task within an if statement

After pressing a button, it triggers the check function, which then executes the isReady() function to perform operations and determine its truth value. During the evaluation process, the isReady() method may actually return false, yet display "Success" i ...

Include a new course based on a specific situation

Is it possible to conditionally add a specific class using vue js? In my DataStore, I have two values defined in TypeScript: value1: 0 as number, value2: 0 as number Based on the values of value1 and value2, I want to apply the following classes in my te ...

Oops! Issue encountered while trying to read the file "src/core/database/config.ts"

Need help with migrating a database in a Node Nest.JS application. When running the npx sequelize-cli db:migrate shell command, I encountered the following exception: Error details: Error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".t ...

Securing Angular CLI Assets: Implementing canActivate for Protection

I am facing an issue where anyone can access my website's assets using URLs like http://localhost:4200/assets/filename.pdf, even when the user is not logged in. How can I secure these assets by implementing a canActivate guard? An ideal solution woul ...

How can a div be displayed next to another div when it is clicked using angular2?

Is there a way to have another page show up after clicking on a div, like shown in the image below? Before Click: After Click: ...

Looking to execute a service method within an authguard service?

I am a beginner with Angular and I am looking to invoke a service method within the authguard service. The specific service function that I need is as follows. Please note that I do not want to make any changes to this service function. loadOrganizations() ...

Is it possible for input properties of array type to change on multiple components in Angular 9?

Encountering an interesting issue that I need clarification on. Recently, I developed a compact Angular application to demonstrate the problem at hand. The puzzling situation arises when passing an Array (any[] or Object[]) as an @Input property to a chil ...

The connections between module dependencies are unable to be resolved

I'm encountering an issue with the npm link command. Here's the scenario: I have two Angular apps - 1) app-core (published locally) 2) app-main The app-core module has the following dependencies (installed via npm): core rxjs z ...

What is the process for overriding the module declaration for `*.svg` in Next.js?

The recent modification in Next.js (v11.0.x) has introduced new type definitions: For next-env.d.ts (regenerated at every build and not modifiable): /// <reference types="next" /> /// <reference types="next/types/global" /> ...

The datepicker in Angular Material refuses to open when used within a modal dialog box

I successfully integrated an angular material 2 date-picker into a bootstrap modal form: <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">{{title}}</h ...

Verifying User Permissions with Angular 2/4 and API

I am currently in the process of developing an Angular 2/4 application that interacts with an API built in Laravel 5.4. One area I'm seeking guidance on involves checking authentication and permissions on the backend through Angular. I want to verify ...

What is the method for declaring constructor functions as object properties in TypeScript?

I am facing a challenge with typing an object that has a property which is a constructor function. How can I properly define the type for this situation: interface MyObj { constructor: () => ({ init: () => void }) } const myObj = { construct ...

In Angular 8, the routes for children were determined based on a specific condition

Is there a way to dynamically load a component in child routes based on a condition? Here are my routes: const mainRoutes: Routes = [ { path: '', component: MainComponent, canActivate: [AuthGuard], children: [ ... { ...

Leverage the spread operator (or an equivalent method) to transfer all attributes from a solitary mixin

When working with the example below, my goal is to pass only the properties of MyMixedInProps to MyChildComponent using a method similar to the spread operator ({...props}). In my specific scenario, MyMixedInProps is defined in a third-party library (whic ...