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

I'm encountering an Unsupported platform error for Angular installation when using [email protected] Does anyone know how to troubleshoot this issue?

C:\Users\vivek>npm install -g @angular/cli C:\Users\vivek\AppData\Roaming\npm\ng -> C:\Users\vivek\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng npm WARN ...

Leveraging vuex in conjunction with typescript allows for efficient management of state in namespace modules,

I am currently integrating vuex with typescript and namespaces module in my project. Within this setup, I have two distinct modules: "UserProfile" and "Trips". So far, everything is functioning smoothly within the confines of each module. However, I have ...

How to Implement Modal Popups on Click in Angular with the AmCharts XY Chart

Our goal is to display a modal window when users click on a data point. The current code we are using is as follows: constructor(public dataservice: DataserviceService, private modalService: NgbModal, private router: Router) { } ... ... bullet.events.on( ...

Internationalization in Angular (i18n) and the powerful *ngFor directive

Within my Angular application, I have a basic component that takes a list of strings and generates a radio group based on these strings: @Component({ selector: 'radio-group', templateUrl: `<div *ngFor="let item of items"> ...

The type 'undefined' cannot be assigned to type 'Element or null'

One of the components I am using looks like this: const data: any[] = [] <Tiers data={data}/> This is how my component is structured: const Tiers = ({ data, }: { data?: any; }) => { console.log('data', data?.length!); ...

I am interested in creating an input range slider using React and TypeScript

This code was used to create a slider functionality import { mainModule } from 'process'; import React, { useState } from 'react'; import styled from 'styled-components'; const DragScaleBar = () => { const [value, setV ...

The property 'ngForOf' cannot be bound to 'li' because it is not recognized as a valid property

I've encountered the ngFor error even after importing the CommonModule and BrowserModule. The issue persists. The browser console is showing the error related to ngFor: adduser.component.html <div class="ui segment"> <ul> & ...

Disable inline imports when implementing an interface in vscode by selecting the "Implement interface" option

When using TypeScript, if I perform an auto-fix on a class name by selecting "Implement interface", it will generate the methods with inline imports like this: getInbox(): Observable<import('../../model/Message').Interactions[]> { t ...

Tips for preserving data upon page refresh in angular 2/4

As a newcomer to Angular2/4, I am facing an issue where the details fetched and saved in my interface are disappearing upon interface refresh. How can this problem be resolved without losing the interface details after a refresh? Here is my Login.componen ...

Is it possible to utilize a JSON file as a JavaScript object without directly importing it into the webpack compiled code?

While initiating the bootstrap process for my Angular hybrid app (which combines Angular 7 and AngularJS), I am aiming to utilize a separate config JSON file by storing it as a window variable. Currently, I have the following setup: setAngularLib(AngularJ ...

Sharing Angular 2 modals across different components

My Angular 2 app consists of several components, including a modal component that I added from here. Now, I want to find a way to use the same modal across multiple components. Is it possible to have one modal open when different buttons are clicked in var ...

The ngOnChange() function in Angular 2 is not behaving as expected when called for the

I am currently working in Angular2 and facing an issue with passing data from one parent component to a child component. <app-datatable-repr [myFilterData]="filterData"></app-datatable-repr> The data being passed is stored in an object called ...

Looping inside a loop with Angular's ngFor

I am working on an Angular + Firebase app. Within one of my components, I am retrieving elements from the Firebase DB and binding them into a template using *ngFor: <div *ngFor="let comment of (comments | async)> <div>{{ comment.text }}< ...

Automatically convert TypeScript packages from another workspace in Turborepo with transpilation

I have set up a Turborepo-based monorepo with my primary TypeScript application named @myscope/tsapp. This application utilizes another TypeScript package within the same repository called @myscope/tspackage. For reference, you can view the example reposit ...

Is it possible to duplicate a response before making changes to its contents?

Imagine we are developing a response interceptor for an Angular 4 application using the HttpClient: export class MyInterceptor implements HttpInterceptor { public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<an ...

Repetitive cycling through an array

My array consists of classes: const transferClasses = [ { id: "c5d91430-aaab-ed11-8daf-85953743f5cc", name: "Class1", isTransfer: false, children: [], }, { id: "775cb75d-aaab-ed11-8daf-85953743f5cc", ...

Transferring data seamlessly from EF .NET Core 6 to Angular

I am facing an issue while trying to fetch data from my ASP.NET Core 6 backend to Angular: Error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed export class EmployeesListComponent { em ...

The error message "Uncaught TypeError: emit is not a function in Vue 3" indicates

As I implemented the code in the Vue 3 setup block to retrieve the input value according to this answer, here is a snippet of the code: import { defineComponent } from "vue"; import { defineProps, defineEmits } from 'vue' export defaul ...

Display the map using the fancybox feature

I have added fancybox to my view. When I try to open it, I want to display a map on it. Below is the div for fancybox: <div id="markers_map" style="display:none"> <div id="map_screen"> <div class="clear"></div> </div&g ...

Troubleshooting: The issue of ngModel being undefined in Angular2 with the <input> element

I am currently working with Angular2 and a modified version of Semantic-UI that includes a calendar module. I am utilizing the `calendar` and `dropdown` functionalities: constructor() { setTimeout(() => { jQuery('.ui.dropdown').dr ...