The switchMap function is sending back a single item

I'm having an issue with switching the observable using the switchMap operator:

return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, {
    query: {
      orderByChild: 'deleted',
      equalTo: false
    }
  })
  .map((locations:any)=>{
    console.log(JSON.stringify(locations,null,2));
    return locations.map(location=>{
      return location.$key;
    });
  }).flatMap(locations=>{
    return locations
  }).switchMap(location=>{
    console.log(location);
    return this.db.object(`Devices/${location}`)
  })
  .do(console.log);

Instead of getting an array of observables, I'm only receiving one observable.

I want to receive an array of "this.db.object(Devices/${location})"

Is there a solution for this problem?

Thank you.

Answer №1

If you're looking to combine multiple observables into a single submission, consider using the forkJoin method. Here's an example of how you can achieve this:

return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, {
    query: {
      orderByChild: 'deleted',
      equalTo: false
    }
  })
  .map((locations:any)=>{
    console.log(JSON.stringify(locations,null,2));
    return locations.map(location=>{
      return location.$key;
    });
  }).switchMap(locationKeys =>{
    console.log(location);
    const locationObs = locationKeys.map((key) => this.db.object(`Devices/${key}`);
    return Observable.forkJoin(...locationObs);
  })
  .reduce((acc, location) => [...acc, location], []);
  .do(console.log);

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

The Vue3 counterpart of vNode.computedInstance

I'm currently in the process of upgrading my app from Vue2 to Vue3, but I've hit a roadblock when it comes to dealing with forms. For my form elements, such as FormInput, FormTextArea, and FormCheckbox, I have been using Single File Components ( ...

Running Jest encounters errors when there is ES6 syntax present in the node modules of a create-react-app project

Currently, I am working on a project using create-react-app and attempting to perform unit testing on a component from office-ui-fabric-react using Jest and Enzyme. The most recent version of office-ui-fabric-react utilizes es6 syntax which is causing iss ...

How can I define Record values in Typescript based on their specific keys?

I am working on creating a custom data structure that allows me to store values with string keys within the union string | number | boolean: type FilterKey = string; type FilterValue = string | number | boolean; type Filters<K extends FilterKey, T exten ...

Recommendations for Organizing Multiple "Isolated" Applications Using MVC 5 and Angular 2

We are currently managing a large MVC 5 ASP.NET 4.5.1 web application that follows the concept of treating each page as its own application due to the vast areas it covers. The existing pages are built using JQuery, regular Javascript, and Handlebars templ ...

Sending information to a PHP script using Ajax

I am working on a project that involves input fields sending data to a PHP page for processing, and then displaying the results without reloading the page. However, I have encountered an issue where no data seems to be passed through. Below is my current s ...

Ways to manage multiple Observables

Two Observables are being returned from different services, each providing only one value (similar to Observable.just()). In TypeScript, types play a crucial role in this context. Is there a method to determine when both Observables have been resolved (in ...

Adding TypeScript to your Vue 3 and Vite project: A step-by-step guide

After setting up my project by installing Vue and Vite using the create-vite-app module, I decided to update all the packages generated by 'init vite-app' to the latest RC versions for both Vue and Vite. Now, I am interested in using TypeScript ...

Assigning a new classification to the primary object in the evolving array of objects

I'm working with an element that loops through all the objects using v-for and has a CSS class named top-class{}... I need to dynamically add the top-class to the first object (object[0]) and update it based on changes, removing the old top-class in t ...

What are some creative ways to emphasize certain dates?

Is there a way to customize mui-x-date-pickers to highlight specific days from a Date array with green filled circles around them? I am using new Date and wondering how to achieve this effect. Below is the code snippet I am currently working with: <Dat ...

The Express application encounters a 500 Internal Server Error due to a TypeError where the Object #<EventEmitter> does not contain the method 'hr

The staging instance of my webapp is encountering an issue: Express 500 TypeError: Object #<EventEmitter> has no method 'hrtime' at Object.logger [as handle] (F:\approot\node_modules\express\node_modules\connect ...

Error encountered during Typescript compilation in Angular9 using Babylon4.1.0 - Unable to locate 'react' module or namespace 'JSX' not found

I am currently encountering compilation issues with Babylon4.1.0 within an angular9 app. It appears that the inspector is having trouble importing the internally used "react" module. To reproduce the issue: * Create a new angular9 app using the CLI * Add @ ...

Retrieving values of checked boxes in a table using JavaScript

While using the select method, I had this line of code: Person_name = $('#selectedPerson').val() When selecting 2 values, person_name.length displays as 2. Recently, I switched to checkboxes displayed in a table. However, when I use person_name ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...

How can you establish an environmental variable in node.js and subsequently utilize it in the terminal?

Is there a way to dynamically set an environmental variable within a Node.js file execution? I am looking for something like this: process.env['VARIABLE'] = 'value'; Currently, I am running the JS file in terminal using a module whe ...

Caution: The `id` property did not match. Server: "fc-dom-171" Client: "fc-dom-2" while utilizing FullCalendar in a Next.js environment

Issue Background In my current project, I am utilizing FullCalendar v5.11.0, NextJS v12.0.7, React v17.0.2, and Typescript v4.3.5. To set up a basic calendar based on the FullCalendar documentation, I created a component called Calendar. Inside this comp ...

Bug in toFixed causing incorrect results

function calculateTaxAndTotalRent(rent) { var phoneCharges = parseFloat($('#phone_charges').val()); phoneCharges = phoneCharges.toFixed(2); rent = parseFloat(rent); rent = rent.toFixed(2); var tax = parseFloat((rent * 15) / 1 ...

Learn how to hide a bar after clicking the "I agree" button with the help of Bootstrap

click here to see imageIs there a way to make that bar disappear once the user clicks "I agree"? I've searched through Bootstrap documentation but couldn't find a solution. Please assist. Below is the code snippet: <div id="cookie-message" cl ...

What is preventing me from including an additional parameter in a function in TypeScript?

I am currently developing a task management application. I am facing an issue while attempting to incorporate the event and items.id into a button function for actions like delete, edit, or mark as completed. While this functionality works smoothly in pla ...

Exploring the concept of returning objects in jQuery

I'm really trying to grasp the inner workings of how jQuery creates the return object when searching for DOM elements. I've delved into the source code, but I must admit that it's not entirely clear to me yet. So, I'm reaching out here ...

An issue arises in Typescript when attempting to pass an extra prop through the server action function in the useForm

I am struggling with integrating Next.js server actions with useFormState (to display input errors on the client side) and Typescript. As per their official documentation here, they recommend adding a new prop to the server action function like this: expo ...