I need RxJs to return individual elements to the subscriber instead of an array when using http.get

I've been developing an Angular 2 app (RC5) with a NodeJS backend RESTful API integration.

One specific route on the backend returns an array of 'Candidates':

exports.list = function (req, res, next) {
  const sort = req.query.sort || null
  const fields = req.query.fields || null

  let query = Candidate.find()

  if (sort !== null) {
    query.sort(sort.replace(',', ' '))
  }

  if (fields !== null) {
    query.select(Candidate.reduceFields(fields))
  }

  query
    .then(function (candidates) {
      res.send(candidates)
    })
    .catch(next)
}

In the frontend service, I fetch this data like so:

  getCandidates() {
    return this.http
      .get(`http://localhost:3500/api/v1/proboard/candidates`)
      .map(function (res) {
         console.log("First:" + res.json());
         return res.json();
      })
   };  

When the controller subscribes to this observable:

ngOnInit() {
    this.subscription = this.candidateService.getCandidates()
      .subscribe(
        (candidates: Candidate[]) => {
          console.debug("Got:" + JSON.stringify(candidates));
          this.candidates = candidates;
         }
      );
  }

It works as intended in terms of retrieving the data. However, the issue is that the controller receives an array of objects from the stream, not individual elements as desired.

For instance, if there are 20 candidates returned, the subscription code only runs once and the controller gets an array of 20 elements altogether.

What I actually aim for is the subscription code to run 20 times, each time with a single element instead of receiving the entire array at once.

I realize that my understanding of how RxJs operates is lacking. How should I modify this code so that the controller fetches one element at a time rather than the entire array simultaneously?

The reason behind this modification is because I ultimately want to receive updates to the candidate list while the controller is active, not just the initial list.

Answer №1

I encountered a similar need within my application.

Modification:

this.subscription = this.candidateService.getCandidates()
                        .subscribe(...);

Instead, try:

this.subscription = this.candidateService.getCandidates()
                        .switchMap(candidates => Observable.from(candidates))
                        .subscribe(...);

Answer №2

The data sent by your back-end is in the form of an array, causing your front-end observable to emit the entire array at once.

If you need each element of the array to be emitted separately by the front-end observable, you must use specific operators when creating it instead of relying solely on the map operator. Consider using the from operator for this purpose.

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

Looking for a drum set with clickable buttons? Having trouble changing the background color in CSS/HTML? Wondering how to map keyboard keys to HTML buttons?

Behold my HTML creation: <H1> <center> EPIC GUITAR JAM </center> </H1> <img class="guitar" src="guitar.jpg" /> <button class="strum" onclick="Strum()"> Strum Chord </button> <button class="pluck" o ...

Troubleshooting: Icon missing from React vscode-webview-ui-toolkit button

In the process of developing a VSCode extension using React and the WebUi Toolkit library for components, I encountered an issue with adding a "save" icon to my button. I diligently followed the documentation provided by Microsoft for integrating buttons i ...

Steps to convert a phone number into JSON format

The primary focus Upon receiving an MQTT packet, it is displayed as an ASCII array in the buffer after being printed using stringify: packet = { "cmd": "publish", "retain": true, "qos": 1, "dup& ...

What is the best way to transmit JSON data to a Web API?

As I work on developing a website with web API integration, I encountered an issue while trying to send JSON data to my controller. Multiple actions were found that match the request: Post on type AuctionWebsiteASP.Controllers.MovesController readDatab ...

When running `aws-cdk yarn synth -o /tmp/artifacts`, an error is thrown stating "ENOENT: no such file or directory, open '/tmp/artifacts/manifest.json'"

Starting a new aws-cdk project with the structure outlined below src └── cdk ├── config ├── index.ts ├── pipeline.ts └── stacks node_modules cdk.json package.json The package.json file looks like this: " ...

Modifying the maximum value of a number field attribute in jQuery after a successful action

As I continue to learn jQuery, I encountered a situation with the following form: <form class="simple-checkout" enctype="multipart/form-data" method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>"> <input type="hidd ...

Is it possible for Javascript, AJAX, or JQuery to determine if a form has been manually inputted into

My goal is to change the contents of a form field and submit the form through the console. However, when I use either jQuery or JavaScript to modify the field and submit it, the page only recognizes values that were manually typed in. In the code snippet ...

Is it possible to transmit messages from a Chrome extension to a Java server?

My question is, if I want to create a Chrome extension that sends messages to a Java server, should I use the XmlHttpRequest API in the extension and have the Java server as an HTTP server? ...

Interactive Vue.js canvases that adapt and respond to various

I am currently working on adjusting my canvas to fit within its container in a Vue component. When I call resizeCanvas() in the mounted hook, I notice that the container's height and width are both 0. How can I create a canvas that dynamically fits it ...

Form control identifier and input field name

I am currently developing a custom input feature for my application. One of the functionalities I want to include is auto-completion, and in my research, I found out that certain conditions need to be met for it to work: In order to enable auto-completi ...

The Bulma calendar date input fails to display the pre-filled start date

I am facing a challenge while trying to integrate the Bulma calendar into my project, particularly when it comes to setting a default start date. According to the documentation, I am using the following method: <input type="date" data-start-date="10/2 ...

Leveraging the result of one ajax function within a different ajax function

My current project involves the following steps: 1. User creates a template with various elements. 2. When the user clicks a button: *The first ajax function establishes a new entry in the custom template database. *The second ajax function retrieves the ...

The React Quill interface is unable to load due to an undefined window

I recently integrated React Quill into my Next.js project and everything was functioning properly. However, I encountered an issue when attempting to incorporate ImageResize into the editor. Upon adding the line Quill.register('modules/imageResize&ap ...

The compatibility issue between Angular JS App and JSPDF is causing malfunctions specifically in Internet Explorer

I am currently working on an Angular JS application that utilizes JSPDF for generating PDFs. While the PDF generation functionality works perfectly fine on Chrome, Firefox, and Safari, it encounters issues on Internet Explorer (IE). The specific error mes ...

To dismiss the Div, simply click on any area outside of it. Leveraging the power of SVG, D3

I need a way to hide my div by clicking outside of it. My SVG has a background and a graph with nodes on top of that. I have a special node (circle) on the graph, clicking on which makes a box appear. To show the box, I use the following code: d3.select ...

Run C# script with the assistance of .load jquery

I have searched extensively for similar posts, but none seem to address the specific question I have regarding my project. What I am attempting to do is load different pages (.aspx) in an iframe dynamically. However, instead of using an iframe, I want to r ...

Creating a Docker Image for Node.Js Using Bazel

Reason Behind the Need I am diving into the Bazel world and struggling to find comprehensive references on constructing Docker images for Node.js. My focus lies on a Typescript-based Node.js application that relies on two other Typescript packages. My ul ...

What is the C sharp version of this code structure?

I'm curious to know what the C# syntax is for declaring a property like this: filters: { [arg: string]: string }; ...

An array filled with unique and non-repeating elements

I want to display random country flags next to each other, making sure they do not match. However, my specific case requires a unique solution for dealing with arrays: function displayRandomFlags() { var flagurls = ["ZPlo8tpmp/chi","cJBo8tpk6/sov","QyLo ...

Angular 6 presents a challenge in rendering data within the multi select drop down feature

I am currently utilizing a multi-select library called ng-multiselect-dropdown in my Angular v6 project. Unfortunately, when I try to display my list using the multiSelect feature, the drop-down shows a message saying "No data available". I discovered th ...