Angular 11 along with RxJS does not support the combineLatest method in the specified type

Hey there, I'm currently working on utilizing the combineLatest operator to merge two streams in Angular, but I keep encountering an error message stating that "combineLatest does not exist on type". I've attempted to move the code into a .pipe() function, however, it doesn't seem to resolve the issue. Should I possibly use map before combining using combineLatest? Appreciate any help you can provide!

import { Injectable } from '@angular/core';
import {Subject, BehaviorSubject, Observable, combineLatest} from 'rxjs';
import { filter, map, scan } from 'rxjs/operators';

// Importing models and services
import {Thread} from './thread.model';
import {Message} from '../message/message.model';
import {MessagesService} from '../message/messages.service';

import * as _ from 'lodash';



@Injectable({
  providedIn: 'root'
})
export class ThreadsService {
threads: Observable<{[key:string]: Thread}>; // (a)
orderedThreads: Observable<Thread[]>; // (a1)
currentThread: Subject<Thread> = new BehaviorSubject<Thread>(new Thread()); // (a2)
currentThreadMessages: Observable<Message[]>; // (a3)

  constructor(public messagesService: MessagesService) { 
    
    this.threads = messagesService.messages // (b)
      .pipe( map((messages: Message[]) => {
        const threads: { [key: string]: Thread } = {}; //(b1)

        messages.map((message: Message) => { // (b2)
          this.threads[message.thread.id] =
            this.threads[message.thread.id] ||
            message.thread;

          const messagesThread: Thread = // (c)
            threads[message.thread.id];
          if (!messagesThread.lastMessage || messagesThread.lastMessage.sentAt < message.sentAt) {
            messagesThread.lastMessage = message;
          }
        });
        return threads;
      }))
      
    this.orderedThreads = this.threads // (d)
      .pipe(map((threadGroups: { [key: string]: Thread }) => {
        const threads: Thread[] = _.values(threadGroups);
        return _.sortBy(threads, (t: Thread) => t.lastMessage.sentAt).reverse();
      }));  

      this.currentThread.subscribe(this.messagesService.markThreadAsRead); // (e1)

    this.currentThreadMessages = combineLatest([this.currentThread, messagesService.messages]).pipe(
      map(currentThread: Thread, messages: Message[]) => {
        if(currentThread && messages.length > 0) {
      return _.chain(messages)
        .filter((message: Message) => // (f1)
          (message.thread.id === currentThread.id))
        .map((message: Message) => {
          message.isRead = true;
          return message;
        })
        .value();
    } else {
      return [];
    }
  }
);
    }

  setCurrentThread(newThread: Thread): void { // (e)
    this.currentThread.next(newThread);
  }
}

Answer №1

One issue at hand is your utilization of the .combineLatest method on an Observable. The correct syntax for employing combine latest is as follows:

newObservable$ = combineLatest([observable1$, observable2$, ...]).pipe(...)

In this scenario, you may implement the following:

 this.currentThreadMessages = combineLatest([this.currentThread, messagesService.messages]).pipe(
  map(currentThread: Thread, messages: Message[]) => {
     if (currentThread && messages.length > 0) {
          return _.chain(messages)
              .filter((message: Message) => // (f1)
                (message.thread.id === currentThread.id))
              .map((message: Message) => {
                message.isRead = true;
                return message;
              })
              .value();
        } else {
            return [];
        }
  }
)

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

Transforming react.js into HTML and CSS programming languages

I have a small experiment I need help with. As I am not familiar with react.js, I would like to convert my main.jsx file into pure HTML/CSS/JS without using react. The issue I'm facing is how to handle form data submission to the server in vanilla HTM ...

Capable of generating a string-keyed map that results in an "Unexpected number error" when the key is referenced

Take a look at the following code snippet: var arr = [{"id":"123", "name":"Jyotirmoy"}]; var mapObj = {}; for(var i=0; i < arr.length; i++){mapObj[arr[i].id] = arr[i];} After creating the map, attempting to access it using the key 'mapObj.123&ap ...

Disabling an Angular MSal route guard based on the environment variable's condition

My routing module is set up with MsalGuard to require authentication for child routes. While this works, I want to disable MsalGuard based on an environment variable when testing locally. How can I achieve this? I attempted using canDeactivate on my rout ...

Set the default page for the p-table

My English proficiency is lacking. I am currently using a p-table with pagination, but I need to modify the pagination in the HTML code. <p-table #dt [columns]="cols" [value]="values" [paginator]="true" [rows]="10" (onFilter)="filtra ...

Coloring a table in vue.js based on performance rankings

I'm facing an issue with sorting my data performance in vue js. Here is the script I have created so far: <template> <div> <div class="row"> <h2> Campaign Performance </h2> <table class=&q ...

Explore bar with search button

I'm facing an issue with the code I have for searching on my website. Currently, when a user fills in their search word and presses enter, it executes the command. However, I would like to only run the search script when the user clicks a button inste ...

Pairing items in a list using the concept of functional programming

Looking to arrange an array by grouping items together? For example: [1, 1, 0, 1, 0, 1, 0] => [1, 1, 0, 1, 1, 0, 0] OR [1, 1, 0, 1, 0, 1, 0] => [[1, 1], [0], [1, 1], [0, 0]] In this scenario, the goal is to group 1s with a maximum group size of 2 ...

Combining an array of objects in Angular 2 based on the object's name

When I receive a response from the backend, it looks like this: [ { "id": 1, "restaurant_name": "Ajisen Ramen Toronto", "description": "Japanese Restaurant", "phone": "416-977-8080", "address": { "id": 3, ...

The validation directive is run on each individual item within the ng-repeat loop

As I develop a single page application utilizing Angular and Breeze, the challenge of managing entities with dynamic validation arises. With a set of entities displayed on the page using data-ng-repeat, I implement in place validation through toggling betw ...

Javascript skips the if-else block when used asynchronously

I'm struggling with an if-else block in my code that is not getting executed as expected. Despite rearranging the code to ensure the if-else condition is met before calling http.get(), I am still facing issues. This problem arises while working with A ...

Why does socket.io have trouble connecting when clients are using different IP addresses on separate wifi networks?

I've encountered an issue where socket.io won't connect when clients are on different wifi networks (ip address) using my self-configured Ubuntu Nginx server. Strangely enough, it works perfectly fine on a pre-configured Heroku server. Here is a ...

Using the methods res.render() and res.redirect() in Express.js

I'm facing a challenge with a route in my express app, where I need to achieve the following: Retrieve data from an external source (successful) Show an HTML page with socket.io listening for messages (successful) Conduct lengthy calculations Send a ...

Tips for sequentially calling multiple await functions within a for loop in Node.js when one await is dependent on the data from another await

I am currently facing a challenge where I need to call multiple awaits within a for loop, which according to the documentation can be performance heavy. I was considering using promise.all() to optimize this process. However, the issue I'm encounterin ...

How to retrieve values from multiple mat-sliders that are dynamically generated using ngFor loop

Creating multiple mat-sliders dynamically in Angular looks like this: <ng-container *ngFor="let parameter of parameterValues; let i = index;"> <mat-slider (input)="onInputChange($event)" min="1" max="{{ parameter.length }}" step="1" value="1" i ...

Can a Javascript file be concealed from view?

Imagine a scenario where the localhost root file is served an HTML file using the following code: app.get('/', (req, res) => res.sendfile('index.html')) Is it possible to include JavaScript files in the HTML document that are not a ...

Is it possible to use string indexes with jQuery each method in Typescript?

When running a jQuery loop in Typescript, I encountered an issue where the index was being reported as a string. $.each(locations, (index, marker) => { if(this.options && this.options.bounds_marker_limit) { if(index <= (this.opt ...

Having trouble retrieving the parent object in Angular OnInit method?

I am facing an issue with attaching a custom validator to an Angular Form Control. The Form Controls are initialized in the ngOnInit method, and I want the validator to check if a field has input only when a boolean class member this.shouldCheck is true. ...

Extension for Chrome - Personalized pop-up notification when page loads

I am looking to create a custom alert box that triggers on page load instead of the default one, which I find unattractive and possibly irritating for users. alert('hello'); My current approach involves the following code: manifesto.js "cont ...

Converting JSON into key-value pairs using ReactJS

Here is a JSON object that I have: [ { "crime": "LARCENY-NON_VEHICLE", "count": "23217" }, { "crime": "AUTO_THEFT", "count": "13675" ...

Is the array index a string or a number?

Why is it that when looping over the indexes of an array they appear as strings, even though using a string to index an array is not allowed? Isn't this inconsistency puzzling? for (const i in ["a", "b", "c"]) { console.log(typeof i + " " + i + " " ...