What is the best way to streamline the response with RxJs?

At this moment, I am using the following code for the operation mentioned in the title:

from(["url_1", "url_2"])
  .pipe(
    concatMap(url => this.vocabularyService.getSimilarProducts(url)
      .pipe(concatMap(x => x.items))
    ),
    toArray()
  )
  .subscribe(res => console.log(res));

This code works by making an API call for each URL in the array of URLs, returning a response similar to this:

class Response {
   items: Object[]
}

Upon receiving the response, another concatMap() is used to retrieve each item in the items array and ultimately flattening them into a single array with toArray(), finally logging it into the console.

I'm curious if RxJs provides any specific operator for handling this process more efficiently, perhaps without the need for multiple nested concatMap() operators?

Answer №1

If you want to compress the array, you can utilize the reduce method.

import { Component } from "@angular/core";
import { from, of } from "rxjs";
import { concatMap, reduce } from "rxjs/operators";

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular';
  subscriber = {
    next: (i) => console.log(i),
    complete: () => console.log('end'),
  };

  ngOnInit() {
    from(['url_1', 'url_2'])
      .pipe(
        concatMap((url) =>
          of({
            items: [1, 2, 3],
          })
        ),
        reduce((acc, one) => {
          acc.push(...one.items);
          // eliminate all duplicates!
          return [...new Set(acc)];
        }, [])
        // shorter version
        // reduce((acc, one) => [...acc, ...one.items], [])
      )
      .subscribe((res) => console.log(res));
    // Check the console at the bottom right corner for results.
  }
}

Check out stackblitz

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

Ways to continuously monitor a div for a specific class

Is there a way to continuously check if an area has the class "top-nav" in order for the alerts to work every time it lacks or contains the class? How can I achieve this functionality? Check out the code on jsfiddle: https://jsfiddle.net/jzhang172/117mg0y ...

Tips for accessing the 'Show More' feature on a webpage with lazy loading functionality

My aim is to click the 'Show More' button on a website. I have written this code, but an error occurs below it. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait #Launch Chrome driver=webdriver.Chrome(execut ...

Is there a way to utilize flex or other CSS properties to wrap element content onto the next line, beginning from the start of its container?

Is there a way to wrap the text content of an element onto the next line, starting from the beginning of its container? I'm looking for something similar to the image provided. Can this be achieved using flexbox or other CSS properties? Here's a ...

Is it possible to render the v-for value dynamically?

I have a dynamic component and I'm trying to iterate through different objects from it. However, my current code isn't working as intended. Can someone please guide me on how to make the activeQuestion value in v-for dynamic? Thank you for your a ...

If the token is null, my intention is to return to the sign-up page, but unfortunately, I am unable to redirect the page back

import React from 'react'; import { AppBar,Typography , Button , Toolbar} from '@material-ui/core'; import {Redirect, useHistory} from 'react-router-dom'; const Admin = () =>{ const history = useHistory(); let ...

Top method to incorporate status verification with javascript

I need to create a system where I can monitor a specific request status from the server side. What is the most efficient method to achieve this without repeatedly sending ajax requests at predefined intervals? One idea I have is to send an ajax request to ...

Tips for avoiding node js from exposing .git directories and its contents

I understand that by using a .htaccess file, I can restrict files from being served under .git. However, I am unsure of how to achieve the same functionality when using a node.js server. I typically use forever to start and stop the servers. Below is the ...

The VueJs input file @change event only triggers once in Chrome after the first call

Here is the code snippet I am currently working with: HTML: <input id="task-message-input-upload" type="file" ref="file" @change="handleFileUpload($event)" /> Javascript : data() { return { uploadedFiles: [], show ...

Browsing through a collection of JSON objects with a user interface

I need a way to filter and display a list of Dogs based on a search query. I initially stored the data in an array within the state, but with an increasing number of entries, I've decided to switch to JSON format for better management. However, I&apo ...

Stop GIFs from playing automatically

Looking for a solution to disable autoplay for animated gifs on my chat-site (php-based). Tried script below but out of ideas: <script> myVid=document.getElementsByTagName('img'); function disableAutoplay() { myVid.autoplay=false; m ...

Having trouble with rendering components in React and Bootstrap?

Attempting to display basic Bootstrap components using React. This corresponds to the index.html file: <!doctype html> <html> <head> <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="j ...

What is the best way to direct a Node server to serve an index file located one directory above?

My folder structure is as follows: Everything is housed within the src folder. The file I want to reference is src/index.html, while my node server file can be found at src/server/server.js https://i.sstatic.net/iEmfS.png When I execute the correct node ...

Encountering an issue while attempting to send a POST response through Node Express, specifically an error related

Encountering an error after completing registration, specifically when attempting to respond to the POST request. (user is added to database successfully) express deprecated res.send(status, body): Use res.status(status).send(body) instead auth\regi ...

Instructions for returning a function from within another function and then displaying it upon return

My current state: constructor(props) { super(props); this.state = { temperatureConversion: '', Here is the function I'm using: handleChange = async (value) => { this.setState({ value }); await Axios.ge ...

No element found with the specified exportAs value of "ngForm" on the <form> tag

I am currently experimenting with a template driven form in Angular, but I encountered an error stating **There is no directive with “exportAs” set to “ngForm"** I have made sure to import FormsModule and ReactiveFormsModule in app.module.ts as well ...

Deactivating multiple buttons in JavaScript after a single click: A guide

After experimenting, I've discovered a solution to my issue. I want to deactivate the option buttons in my quiz application once the user has made a selection. The reason for this is because if the correct answer is revealed and the user selects any ...

Employing identification as a variable

I'm currently attempting to retrieve the text within a span element that has a class of "link," but I seem to be encountering some issues. <div id="item-0" class="box"> ....... </div> <div id="item-1" class="box"> <p>& ...

Tips for validating a text input field depending on the selected value in a dropdown menu using AngularJS

When a user selects from the dropdown menu, they can choose between Number and Decimalnumber. If the user selects Number, the text box should only allow whole numbers (e.g. 22, 33, 444, 345436). The user should not be able to enter decimal values like 22 ...

injectIntl requires a component with props containing the `intl` attribute

I'm encountering an issue with the React.ComponentClass type in my project. The TypeScript version I'm using is 2.4.2- Here's the component code: import * as React from 'react'; import { injectIntl, InjectedIntlProps } from &apo ...

Issue: The text.replace function is not working in an AngularJS filter. What steps can be taken to resolve this?

While working in Angular, I attempted to utilize a filter to replace certain strings with different words. Despite trying numerous examples, it seems like my code is missing something crucial that I can't seem to pinpoint. Here's the snippet of m ...