Join the nested Observables array

I have an array that holds objects, each containing two properties where one is an observable value.

let myArray = [{def: 'name1', value: EventEmitter_}, {def: 'name2', value: EventEmitter_}]

My goal is to subscribe to the observables and return the root object in which the change occurred.

Currently, I am only able to get the specific value.

      myArray.forEach(item => {
        item.value.subscribe(val => console.log(val))
      })

I attempted using merge

  merge(myArray).subscribe((value) => {
        console.log(value)
       })

However, this approach does not work if the observable is nested within another object.

Answer №1

One way to handle the data flow is by using piping.

myData.forEach(item => {
  item.value.pipe(
    map(val => [item.definition, val]),
  ).subscribe(([def, val]) => console.log(`Processing ${def}: ${val}`));
})

Answer №2

const combinedObservables = merge(
    ...this.array.map((x: any) =>
      x.value.pipe(map((res) => ({ def: x.def, response: res })))
    )
  );

By merging the transformed "observables" with properties "def" and "response", you only require a single subscription.

For further reference, check out this StackBlitz example.

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

Guide on separating a variable by commas using jQuery

After making an Ajax call to a Java servlet, I am retrieving data and storing it in the 'data' variable upon success. Here is the code snippet: var s1=""; var ticks =""; $('#view').click(function(evt ...

Tips for transfering variables from an electron application to the backend of an Angular project

My goal is to develop a website and desktop application using the same code base. However, due to some minor differences between the two platforms, I need a way for my Angular app to distinguish whether it has been called from the web or from Electron. I& ...

Is there a way to initiate the server only after webpack has finished bundling all of the bundles

"scripts": { "start": "node server.js", "build": "webpack" }, Is there a way to execute both npm run build and npm start with a single command? "scripts": { "start": " ...

Troubleshooting the challenge of transitioning from Angular 4 to Angular 9 with flatMap

In my Angular 4 code, everything runs smoothly: public resolve(): Observable<GridViewDtcConfig> { const permissionResponse = this.flowsService.getPermissions(); return permissionResponse.flatMap((permissions) => { c ...

Ways to reach the Document Object Model in a functional component

While working on a speedometer project in ReactJS with some vanilla syntax, I encountered an issue where the canvas element was returning null. Oddly enough, when running const canvas = document.getElementById('dial__container'); in the console, ...

Is it possible to link actions to a storage location external to a component?

Imagine having a store set up with a middleware called redux-thunk. The store is created and exported using the following code: import myOwnCreateStoreMethod from './redux/createStore'; export const store = myOwnCreateStoreMethod(); Now, you ha ...

Generating numerous responses in Node (sails js) from a solitary function

Currently, I am facing an issue while developing a web application using AngularJS and Sails. The problem arises in my application's menu section where different count values are supposed to be displayed from the database. When I try to retrieve this ...

validate the existence of the username upon submission of the form

Here is some code that I have written. .js $(document).ready(function() { $("#username").focusout(function() { $.ajax({ type:'post', url:site_url()+'/client/checkUserName', data:{&apos ...

When the add button is clicked, I would like to implement a feature where a checkbox is added

When the user clicks on the link "출력하기", I want the web page to add a checkbox to all images. I wrote this code, but it's not working. Can anyone help me? This is my JS: $(document).ready(function(){ $("#print").on('click', fu ...

Tips for obtaining the "inner type" of a particular "instance" in TypeScript's generics

Unable to find more appropriate language to elaborate beyond the title, I'm going to rely on the code itself: let var1 = someExternalLibraryMethod(); // assume var1 is implicitly Promise<string> let var2: typeof var1; // this approach enables ...

What sets apart defining a function in ReactJS using only parentheses versus curly braces within parentheses?

As a newcomer to React, I encountered an interesting application that had functions defined in two different ways. One style was async function (a, b) => {//body}, which I found easy to understand. However, another set of functions followed the struct ...

Enhancing images by creating clickable sections in a more organized and efficient manner

Are there any other methods to make parts of an image clickable in a more organized way, aside from using the coordinates method or directly embedding images from Photoshop? <script> new el_teacher = ["candice","john"]; $(".teacher1").mouseenter(fu ...

In Typescript, is it correct to say that { [key: string]: any } is identical to { [key: number]: any }?

Recently diving into Typescript has been an interesting journey, especially when stumbling upon weird language behaviors. After writing the following code snippet, I was surprised to see that it compiled and executed successfully: let x: { [key: string]: a ...

Sidenav Angular Material cdkScrollable is an effective tool for creating scrollable

In Angular Material CDK, there is a special Directive called CdkScrollable that allows you to monitor ScrollEvents within a specific container. I am currently attempting to retrieve the CdkScrollable associated with the default MatSidenavContent. Unfor ...

Using single quotation marks in Javascript

When the variable basis contains a single quotation mark, such as in "Father's Day", I encounter an issue where the tag is prematurely closed upon encountering the single quotation mark. 'success' : function(data) { div.innerHTML = &apo ...

The Body Parser is having trouble reading information from the form

I'm struggling to understand where I'm going wrong in this situation. My issue revolves around rendering a form using a GET request and attempting to then parse the data into a POST request to display it as JSON. app.get('/search', (re ...

Retrieve the element by its id using JavaScript even when there are no form tags present on the webpage

Is it possible to retrieve an element by its ID using JavaScript when there is no form tag available? I am trying to obtain the value of a textbox with the following command, but I keep receiving a 'null or undefined' error message. It works cor ...

Create PDF on the server side using Asp.Net Core and then display it in the browser using Angular

In my project, I am utilizing Asp.Net Core and ItextSharp to dynamically create a PDF report which is then sent to the browser. [HttpGet] public async Task<IActionResult> GetStream(string ids) { try { List<int> labRequest ...

Lazy loading AngularJS UI router named views is an efficient way to improve performance

AngularJS UI router named views loading based on user access rather than loading at the time of state route access. Example: $stateProvider .state("login", { url: "/login", templateUrl: getTemplateUrl("login/Index") }) ...

Is it possible to continuously re-render a React Functional Component with Axios and useState/useEffect?

Seeking assistance with creating a React Functional Component using Typescript to fetch data from an API and pass it to another component. However, encountering the error message "Error: Too many re-renders. React limits the number of renders to prevent an ...