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

Obtain JSON data using jQuery

Hey there! I am currently working on understanding how to retrieve data using json/JQuery with the code below. After storing a php variable in a json variable (var ar), I confirmed its contents through console.log, although when I used document.write it d ...

Using Meteor methods in a Meteor and Ionic application: A guide

After building the web app with Meteor, I am now looking to develop a new app utilizing both Meteor and Ionic technologies. My goal is to leverage the existing Meteor methods in my Ionic app without duplicating efforts for mobile development. Any suggestio ...

The Battle of node.js Modules: Comparing socket.io and express.static

The server.js file I am currently running is set up as follows: module.exports = server; var express = require('express'); var fs = require('fs'); var server = express.createServer(); var port = 58000; server.listen(port); var ...

Issue with printing data consecutively using Javascript

My JavaScript code aims to display the content of the body tag again when the add button is clicked. The purpose is to add authors, with each author being added in sequence. For example, if there is only 1 author present, the user simply selects whether th ...

Unable to set the height for ul/div elements

I'm struggling to make my navbar appear when I click the "menu button". The div seems to be present in the code, but with a height of 0. Here's the relevant section of the code causing the issue. Any suggestions on how I can resolve this? var ...

Having trouble with creating SQLite tables using JavaScript within a for loop

I have developed a multi-platform app using AngularJS, JavaScript, Phonegap/Cordova, Monaca, and Onsen UI. In order to enable offline usage of the app, I have integrated an SQLite Database to store various data. After conducting some basic tests, I confir ...

Guide to dynamically inserting an audio file into a div with jQuery

I am looking to dynamically insert an audio file. Below are the declared tags: <div> <audio id="myaudio"> </audio> </div> Now, I am trying to add the source dynamically. Can anyone help me with how to add it to the div or audi ...

Create a dynamic animation page using Node.js, then seamlessly redirect users to the homepage for a smooth user

Good day everyone! I've decided to change things up with my latest query. I'm currently working on adding a loading page animation that will show for 3 seconds when visiting the '/' route, and then automatically redirect to the home pag ...

Can terminating a POST XHR request be trusted?

Running an apache server with PHP 5.4. I've set up a form that sends an asynchronous request to the server and stops any previous requests if the button is clicked again before the current request is completed. If I repeatedly click the button quick ...

jQuery struggles to locate the active class within the Bootstrap slider

Want to make some changes to the Bootstrap slider? Here is the HTML Code and jQuery: <div id="carousel-slider2" class="carousel slide bs-docs-carousel-example"> <ol class="carousel-indicators"> & ...

Embracing the Quirks of JSON: A Call for a

Currently, I am in the process of developing a webpage that involves incorporating four distinct JSON entities (objects, arrays). Excuse my lack of appropriate jargon. Upon receiving the JSON data, it is structured as an object with numerous sub-objects, ...

Can you explain the meaning and significance of the @Injectable annotation?

Is the use of @Injectable indicating that we are able to inject MyService into other classes, or does it mean that we can inject other classes into MyService? @Injectable({ providedIn: 'root' }) export class MyService { constructor() { } } ...

"Exploring the process of creating a custom type by incorporating changes to an existing interface

One of the challenges I'm facing is defining an object based on a specific interface structure. The interface I have looks like this: interface Store { ReducerFoo : ReducerFooState; ReducerBar : ReducerBarState; ReducerTest : ReducerTestSt ...

Incorporating an offset with the I18nPluralPipe

Having trouble with my multiselect dropdown and the text pluralization. I attempted to use the I18nPluralPipe, but can't seem to set an offset of 1. ListItem = [Lion, Tiger, Cat, Fox] Select 1 Item(Tiger) = "Tiger", Select 3 Item(Tiger, Cat, Fox) = ...

What is the best way to automatically add a date and timestamp to every new entry?

I am currently working on a project that utilizes AngularJS and Ionic frameworks. The main feature of the project will involve users inputting data to create a list, and allowing any user to comment on each item in the list. One challenge I have encounter ...

Is there a way to immobilize an object in JavaScript without resorting to Object.freeze()?

Is there a way to freeze the following object without relying on Object.freeze()? Let's find out: const obj = { a:'test', b:'Something' } ...

Find the elements of <a> tags specifically without the attribute href

Currently, I am extracting the class of all <a> elements in an HTML document of a webpage using VB.net from a WinForm: Dim htmlLinks As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("a") For Each link As HtmlElement In htmlLi ...

How to reset a form in AngularJS using either HTML or a built-in directive

Within a standard modal popup in Bootstrap, I have implemented a form consisting of input fields, a submit button, a cancel button, and a close-icon. When selecting the name from an Object data-list using ng-repeat, the popup containing the form will displ ...

A step-by-step guide on connecting an event listener to the search input of Mapbox GL Geocoder in a Vue application

I've encountered a challenge trying to add an event listener to the Mapbox GL Geocoder search input within a Vue application. It appears to be a straightforward task, but I'm facing difficulties. My objective is to implement a functionality simi ...

Ways to retrieve all elements based on their class names?

What is the equivalent of using $('.class') in JQuery to get all elements by class name with pure JavaScript? ...