Tips for Achieving Observable Synchronization

I've encountered a coding challenge that has led me to this code snippet:

ngOnInit(): void

       {
this.categories = this.categoryService.getCategories();

            var example = this.categories.flatMap((categor) => categor.map((categories) => {

            var links = this.categoryService.countCategoryLinks(categories.id)
                       .subscribe(valeur => console.log(valeur));
                return categories.id
            }));
    }

The outcome produces two observables. One contains a list of categories, while the other displays the count of items for each specific category.

My inquiry is as follows:

How can I efficiently structure all this information into a unified data format? I aim to group both categories and their respective item counts in a single data structure for seamless representation in my TS component.

After debugging step by step, I have revised the code and achieved a near solution:

this.categories = this.categoryService.getCategories();
        var example = this.categories.mergeMap((categor) => categor.map((myCateg) =>
            {
            this.categoryService.countCategoryLinks(myCateg.id)
                .map(numlinks => Object.assign(myCateg,{numLinks: numlinks}))
                  .subscribe(valeur => console.log(valeur));
            return myCateg.id
        }));

This implementation results in the following output:

https://i.stack.imgur.com/gOeFT.png

However, the numLinks property remains an object... (containing the count value). Any suggestions on transforming it into a JSON property like categoryName or id??

Your assistance is highly appreciated!

Finally, here's the solution to address the issue:

ngOnInit(): void
{
    this.categories = this.categoryService.getCategories();
    const example = this.categories
        .mergeMap((categor) => categor
            .map((myCateg) => {
        this.categoryService.countCategoryLinks(myCateg.id)
            .map(numlinks => {
                myCateg.numlinks = numlinks.count;
                return myCateg;
            })
                //Object.assign(myCateg,{numLinks: numlinks}))
            .subscribe(value => console.log(value));
        return myCateg
    }));

            example.subscribe(val => console.log("value2: "+val));

}

Answer №1

The solution once again relies on the use of the mergeMap() operator. :-)

this.categoryService.getCategories()
  .mergeMap(val => val)  // "Flatten" the categories array
  .mergeMap(category => 
    this.categoryService.countCategoryLinks(category.id)
      // Write the number of links on the `category` object
      .map(numLinks => Object.assign(category, {numLinks: numLinks}))
  )
  .toArray()
  .subscribe(allCategoriesWithNumLinks => console.log(allCategoriesWithNumLinks));

I won't delve into the specific details (like the first mergeMap for flattening the array or the use of Object.assign() to create the final object) since it seems like we already covered that in a prior discussion. However, feel free to ask if anything is unclear.

Philippe's queries:

  • Why flatten the categories array? I'm assuming that getCategories() emits a SINGLE array containing all the categories. To make it easier to run an HTTP request for each category, it's more practical to have an observable emitting each category individually. This is exactly what the initial mergeMap() accomplishes: transforming Observable<Category[]> into Observable<Category>.
  • Why construct an object? You mentioned your desire to keep all data in one structure. That's precisely the purpose of Object.assign: it assigns the number of links found for each category onto the original category object itself. By doing so, you obtain a unified object containing information from both observables (category + numLinks).

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

Unable to submit form upon clicking radio button in .NET Core

Trying to submit a form by clicking on a radio button. The JQuery code used for submitting the form: Form: @for (var item = 0; item < Model.Count(); item++) { <form id="myform" action="xx" controller="xxx" method="post"> ...

Problem with memory management in ThreeJS

After developing a ThreeJS app using the canvas renderer to meet project requirements, I encountered a memory and garbage collection issue. As part of the application logic, numerous meshes are created for animations on sections of a flat 2D donut or ring ...

Tips for retrieving the value from an angular tag using Selenium

Is there a way to retrieve text content that can be seen on the user interface, but is not part of the HTML structure? https://i.sstatic.net/SdibP.jpg ...

Clashing Dependencies in Angular 8

I'm currently working with Angular 8 and I keep receiving npm warnings about angular/compiler-cli peer dependencies. npm WARN @angular/[email protected] needs @angular/[email protected] as a peer dependency, but it is not installed. You h ...

Vue.js v-cloak lifecycle method

Currently, I am working on a project where I have styled v-cloak with display: none, and it is decorating the body. As a result, everything remains hidden until the Vue instance is ready. I have created a component that inserts a chart (using highcharts). ...

Tips on navigating to a URL with a component in React without losing the passed props

When the onClick event is triggered, I aim to redirect to a new component with props passed to it along with a new URL. My App.js import React from "react"; import Main from "./Components/Main/Main"; import "bootstrap/dist/css/boo ...

Why is my jQuery SlideReveal not displaying on page load?

Can anyone provide some help? I am currently using the jquery.slidereveal.js plugin from ''. The plugin works well when manually clicking the trigger to open and close the menu. However, I would like it to default to its last state on page load, ...

Retrieve information from an ajax response in XML format

AJAX Call Code Example $.ajax({ url: '/services/LTLGadgetV2.aspx', type: 'Get', success: function (result) { console.log( result); } }); The response in the console: Sample XML <RateResults xmlns ...

Issue with Angular/HTTP POST request where boolean data is being passed as blank

I've been encountering an issue while trying to send data to an API - specifically, my boolean data is not being transmitted correctly and shows up as blank. I'm curious if anyone has any insights on what might be causing this problem? const noti ...

Executing functions before the data is loaded in an Angular application

Hey there, I'm relatively new to Angular and I've been facing some difficulties when it comes to loading data. In the code snippet below, you'll notice that I have two services being called. Each service logs something to the console. After ...

Customizing CSS based on URL or parent-child relationship in WordPress

I'm having trouble finding a solution for what seems like a simple issue... Currently, my header has a border-bottom and I'd like to change the color of this border based on the section the user is in. For example, consider these parent pages: ...

Prevent Cordova from shrinking the view when focusing on an input

Currently working on developing an app using Cordova/Phonegap (v6.5.0). Platforms where I've installed the app: - IOS (issue identified) - Android (issue identified) - Browser (no issue found) I am facing a known problem without a suitabl ...

Having trouble with bootstrap carousel malfunctioning on Firefox browser?

I'm experiencing an issue with the carousel slider on my website. It seems to only be working in Chrome and not in Mozilla Firefox. You can view the live site at: Below is the code I have used for the carousel: <header id="myCarousel" class="car ...

Is there a comparable Javascript alternative to the Ruby gem "site_prism" for Page Objects design?

Is there a JavaScript framework for Protractor in NodeJS that provides a clean way to define Page Object Elements similar to site_prism? I've explored astrolabe but it doesn't quite meet the requirements. This is an example of how Page Objects a ...

I am attempting to create an API request that is dependent on the outcome of another API request by utilizing a forEach loop. Is there a different approach I could take to achieve the desired

After successfully implementing an API request based on the result of another API request, I am looking for a more efficient method than using forEach for my subsequent API call. Is there a way to achieve this by utilizing Promise.all or any other alternat ...

Assassin eradicated from list of cast members

In my quest to select a killer from the Cast Members Array for the game, I want the function to pick one person as the killer and then remove them from the castMember player array. Once the killer is chosen, they should be removed from the survivors array ...

Error TS2322: Cannot assign type 'Foo | Bar' to type 'Foo & Bar'

I am attempting to save an item in an object using the object key as the discriminator for the type. Refer to the edit below. Below is a simple example: type Foo = { id: 'foo' } type Bar = { id: 'bar' } type Container = { foo ...

Can data be transferred within a callback to the function it encapsulates?

I am currently working on developing a user login system and I find myself in need of querying the database. Being a beginner in coding, I am grappling with the concept of callbacks and how data can be passed once the callback has been executed. My dilemm ...

What is preventing me from invoking the function that I built using the Function() constructor?

Utilizing the Function Constructor within a function to generate functions during its call. Below is the constructor: funcGenerator(f) { return new Function( "value", "try{ return " + f + '; } catch (e) { ret ...

Encountering a problem with AngularJS when attempting to access an array and display an alert message

While working with Angular, I encountered an issue in trying to access content stored within an array. Upon reviewing the code, console.log(JSON.stringify($scope.lineItems)) was returning [[]]. However, when inspecting or setting a breakpoint on this line ...