Include a Thread variable into an Observable variable that holds a collection of key-value pairs of type string and Thread

Let me share with you how I initialize my variable threads:

threads: Observable<{ [key: string]: Thread }>;

Here is the code snippet for initializing my variable threads :

this.threads = messageService.messages
  .map((messages: Message[]) => {
    const threads: { [key: string]: Thread } = {};
    messages.map((message: Message) => {
      threads[message.thread.id] = threads[message.thread.id] ||
        message.thread;

      const messagesThread: Thread = threads[message.thread.id];
      if (!messagesThread.lastMessage ||
        messagesThread.lastMessage.date < message.date) {
        messagesThread.lastMessage = message;
      }
    });
    return threads;
  });

I have a requirement to add a new thread to the existing variable threads :

const newThread: Thread = new Thread(objMessage.id, objmessage.participants);

I attempted the following approaches:

threads = Observable.of([newThread]);

And also this :

this.threads.subscribe((thread: Thread) => {
   threads.next(newThread);
});

Unfortunately, none of these solutions seem to work due to incorrect type assignment.

////////////////////////////////////////////////////////////////////////////

EDIT :

////////////////////////////////////////////////////////////////////////////

By changing my thread variable to BehaviorSubject:

threads: BehaviorSubject<{[key: string]: Thread }> = BehaviorSubject.create();

I had to modify the initialization in the following way :

this.messageService.messages.map((messages: Message[]) => {
  const threads: { [key: string]: Thread } = {};
  messages.map((message: Message) => {
    threads[message.thread.id] = threads[message.thread.id] ||
      message.thread;

    const messagesThread: Thread = threads[message.thread.id];
    if (!messagesThread.lastMessage ||
      messagesThread.lastMessage.date < message.date) {
      messagesThread.lastMessage = message;
    }
  });
  return threads;
}).subscribe(threads => {
  this.threads.next(threads);
});

Additionally, I added :

addThread(newThread: Thread): void {
  this.threadService.newThreads.push(newThread);
  this.threadService.newThreadsId.push(newThread.id);

this.threadService.orderedThreads.next(this.threadService.newThreads);

let threads = this.threadService.threads.value;
this.threadService.threads.next(threads);
}

After executing the above logic, an error occurred :

Cannot set property 'flo' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot set property 'tRev' of undefined

'flo' refers to the id of my Thread :

this.addNewMessageNewThread({
  "id": "flo",
  "author": "Flo Peron",
  "body": "COUUUUCOU",
  "title": "Groupe 158"
});

Answer №1

It seems like what you're looking for is a subject rather than an observable. Specifically, you may want to consider using a behavior subject if you need to update the current value.

categories: BehaviorSubject<{[key: string]: Category}>;

productService.products.map(...).subscribe(categories => {
  this.categories.next(categories);
});

addCategory(key: string, category: Category) {
  let categories = this.categories.value;
  categories[key] = category;
  this.categories.next(categories);
}

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

Using React.PureComponent, the list component efficiently renders each item with optimized performance

We've developed a reusable list component in ReactJS. To address performance concerns, we decided to incorporate the shouldComponentUpdate method to dictate when our list component should re-render. public shouldComponentUpdate(nextProps: TreeItemInt ...

Utilizing the input element to modify the font color of the title upon clicking the button

I've been honing my skills in Angular and facing an issue with altering the font color of a variable called title. I'm struggling to figure it out. Take a look at the code snippet from tools.component.ts: [...] title: string = 'Add note ...

Typescript error: Cannot access property "status" on type "never".ts(2339)

Currently, I have a method that utilizes nextjs/auth to sign in with credentials from a form. However, I am encountering a type checking error Object is possibly 'undefined'.ts(2532) const doStuff = async (values: any) => { const result: S ...

I'm seeking a way to have this specific method called from the Angular frontend using a POST request. I need help in implementing the function within my Angular code to successfully invoke the POST method

This code snippet demonstrates my approach in the .NET uploadController: [Produces("application/json")] [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status202 ...

Issues with Cognito integration in setting up a Cloudfront Distribution for hosting static content on S3

I've been facing an issue with my S3 website behind a CloudFront distribution when trying to authenticate with Cognito. Everything works perfectly when testing my Angular app locally with Callback URL and Sign out URL set to localhost:4200/. https:// ...

Updating the sidebar component in Angular 11 post successful login

Recently, I delved into the world of Angular with a goal to learn more about its functionality. I encountered an issue with my sidebar component that remains static even after logging in: Click here to view my sidebar text Upon successful login, the regi ...

Troubleshooting Problem with Angular 12 FormData API

Encountering challenges when attempting to send FormData from an Angular 12 application to a .Net Core API. Every try to transmit the data results in denial during preflight and never triggers the backend endpoint (validated with Console.WriteLine). Follo ...

The type 'Observable<any>' cannot be assigned to the type 'Observable<T>'

Here is the code I am working with: import {HttpClient} from '@ngular/common/http'; private httpClient: HttpClient; do_request(method: string, url: string, ...

Enhancing NgBootstrap with a custom dayTemplate in NgbDatepicker

My webpage features a NgbDatepicker with a customized dayTemplate for enhanced styles and additional information for each day: https://i.sstatic.net/BtCYD.png While it looks visually appealing, the performance is unbearably slow, causing the page to free ...

Updating the parent component upon navigating from the child component in Angular app

Struggling with updating the parent component after routing from a child component. Through research, I've learned that ngOnInit only runs once. Any way to work around this issue? I've experimented with different lifecycle hooks, but no luck so f ...

Warning: React has detected that a non-boolean value of `true` was received for the attribute `my-optional-property`

source code import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps extends ButtonProps { "aria-label": string; "my-optional-property"?: boolean; } function MyCustomButton(props: MyButtonProps) { ...

What is the best way to assign JSON values to my class property?

I've been working on a weather application that showcases the current weather of 5 different cities. By clicking on each city, users can access a detailed view displaying the 5-day forecast for that particular location. Currently, I have defined a we ...

The TS2583 error in TypeScript occurs when it cannot locate the name 'Set' within the code

Just started my Typescript journey today and encountered 11 errors when running tsc app.ts. Decided to tackle them one by one, starting with the first. I tried updating tsconfig.json but it seems like the issue lies within node_modules directory. Any help ...

Gathering the presently unfinished observables within a superior-level rxjs observable

As an illustration, let's consider a scenario where I have a timer that emits every 5 seconds and lasts for 10 seconds. By using the scan operator, I can create an observable that includes an array of all the inner observables emitted up until now: c ...

Dealing with Angular's observables and behavior subjects is really throwing me for a loop. I just can't seem to find the right way to refactor

Although the title may be a bit vague, I will clarify with an example from a service of mine. Essentially, I have a service in my application that allows me to set a source from a list of sources retrieved from the backend, which various parts of my app u ...

Creating custom views in Angular 8 based on user roles through directives

After reviewing an example on how to display components based on a user's role at this link: I'm encountering compilation issues due to missing arguments in the constructor within has-role.directive.spec.ts. The constructor in has-role.directive ...

Is there a way to determine if Vue is currently in development mode?

Whenever I run my Vue application, the console output indicates: The running environment is development mode. Make sure to switch to production mode for deployment. For more tips, visit https://vuejs.org/guide/deployment.html Now, I am looking to verify ...

Is there a way to run a URL in Angular2 without having to include the ID like /edit/:id?

Looking to access a specific page in the browser? Instead of the longer URL below: You can use this shorter link to view or edit details for a specific ID in AngularJS 2. ...

Choose a random element from an array in an Angular service

Hey there! I am relatively new to Angular, but I recently used the Angular Hero tutorials to create a website that showcases cooking recipes. The recipes are pulled from a Recipe service, and when you click on a recipe, it shows you all the details. I foll ...

Encountering an issue in the test file when using react-router-dom v6: "The 'history' property is not found on the 'IntrinsicAttributes & RouterProps' type."

Main script: import { useContext, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import AuthenticationContext from './AuthenticationContext'; function HandleOAuthCallbackRoute() { co ...