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

Is there a way to dynamically update a game's highscore from a database without having to refresh the page?

I developed a JS snake game using HTML5 canvas. In the event that the user loses, the score is transmitted to the database through an AJAX call in my PHP script. The PHP code then compares this score to the current highscore and updates it if needed. Howev ...

Let's unravel this JavaScript enigma: the code snippet window.confirm = divConfirm(strMessage) awaits

Imagine a scenario where you have an old website with a lot of existing JS code. If a user wants to update all the alert messages to modern, stylish Div-based alerts commonly used in jQuery, YUI, Prototype, etc., there are primarily three types of JS dialo ...

Revamping JavaScript Code for Better Performance

I've been working on a lot of code in the backend section of my website, mainly dealing with CRUD operations using AJAX calls. Do you have any suggestions on how I can refactor these functions into more generic ones or possibly create classes instead ...

Library package for Selenium web driver

I'm new to using Selenium web driver As I started writing my code, an error occurred in the first line. The package is showing as not accessible." Any assistance would be greatly appreciated. https://i.sstatic.net/vYUmS.png ...

What is the best way to manage horizontal scrolling using buttons?

I was hoping that when the button is clicked, the scroll would move in the direction of the click while holding down the button. Initially, it worked flawlessly, but suddenly it stopped functioning. export default function initCarousel() { const carous ...

What is the best way to retrieve a state variable within the getServerSideProps() function in NextJS?

Introduction Greetings everyone, I am a newcomer to NextJS. Currently, I am in the process of developing a weather application that utilizes external APIs. My main task involves fetching data from an API and displaying it on the frontend. Desired Function ...

What techniques can be employed to dynamically modify Typescript's AST and run it while utilizing ts-node?

Below is my approach in executing a TypeScript file: npx ts-node ./tinker.ts In the file, I am reading and analyzing the Abstract Syntax Tree (AST) of another file named sample.ts, which contains the following line: console.log(123) The goal is to modify ...

Implementing various event listeners for asynchronous JavaScript and XML requests (

Struggling to iterate through an ajax query and encountering a problem where the i value always defaults to 1. I'm not very well-versed in js so any suggestions on how to tackle this issue or possibly a better approach would be greatly appreciated. Th ...

Populating a HTML document with data retrieved from an AJAX request

I have a button that, when clicked, should display the values of a specific user. The code snippet for this functionality is as follows: HTML Button: <button onclick="return getUserDetails(<? echo $user['id']; ?>)" class="btn btn-xs bt ...

Modifying all occurrences of a specified string in an object (or array) - JavaScript

Is there a more efficient way to search through and replace all instances of a given string in a JavaScript object with unknown depth and properties? Check out this method, but is it the most optimal solution? var obj = { 'a' : 'The foo ...

Running a Mongoimport command within a JavaScript/Node.js script

Is there a node.js/javascript library available that allows for the use of mongoimport within code? From what I understand, mongoimport is similar to an .exe file that needs to be executed before being able to utilize its text input environment. Is it fe ...

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...

Set the input's type attribute to 'checkbox' to address an issue with Internet Explorer

This issue is specific to Internet Explorer, as other browsers like Firefox, Chrome, Safari, and Opera are functioning correctly. Instead of displaying checkboxes, it shows a value box... Here is the code snippet: <html> <head> <title> ...

Implementing typing for a module that exports an instance of a particular class

Attempting to create a .d.ts file for the foo-foo-mq module has presented some challenges. Following the documentation, a 'foo-foo-mq' folder was created within the 'typings' directory at the project's root. An index.d.ts file was ...

What is the most effective approach for delivering arguments to event handlers?

Consider the following block of HTML: <button id="follow-user1" class="btnFollow">Follow User1</button> <button id="follow-user2" class="btnFollow">Follow User2</button> <button id="follow-user3" class="btnFollow">Follow User ...

When you reach the end of the page, the loadMore function is triggered multiple times

On my webpage, I have a list of profiles that are displayed. When the user reaches the bottom of the page, more data should be loaded through the loadMore function. While the loadMore function itself works correctly, I am facing an issue with the listener. ...

Implementing pagination in a Node.js application using MongoDB.ORCreating

function implementPaginationForDigitalMigrationJoin(req, res, next) { DigitalMigrationForm.aggregate([ // Join with user_info table { $lookup: { from: DigitalMigrationFormList.collection.name, // other ...

Select a background using the Konvas.js library by clicking on a CSS class

I am attempting to use Konvas.js to change the background when clicking on an image with the imgback class: Link to Code I want to avoid assigning an id to each individual image Here is the code snippet: Jquery: $('.back').click(function(){ ...

Error message: "When using selenium-webdriver in JavaScript, the findElement method for <a> tags cannot be used as a function."&

Seeking the website URL for brand information from this website, I attempted to retrieve it using JavaScript in the console: document.getElementById('phone_number').getElementsByTagName('a')[1].getAttribute('href') However, ...

What is the best way to connect an event in Angular 2?

This is an input label. <input type="text" (blur) = "obj.action"/> The obj is an object from the corresponding component, obj.action = preCheck($event). A function in the same component, preCheck(input: any) { code ....}, is being used. Will it wor ...