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

To toggle the state of an md-checkbox in Angular 2 (or 4) by referencing its unique identifier

<md-checkbox [align]="end" *ngFor="issueConfid in issueConfidences" (change)=onIssueConfidenceFilterChange(issueConfid)" id="favoriteCheck1.name"> {{issueConfid.name}} </md-checkbox> Is there a way to programmatically uncheck or check the ...

guide on creating a simple line highchart using JSON data

Here is the JSON data I have: {"09/02/2014 15:36:25":[33.82,33.42,40.83],"08/11/2014 16:25:15":[36.6,33.42,40.45],"07/30/2014 08:43:57":[0.0,0.0,0.0],"08/12/2014 22:00:52":[77.99,74.1,80.12],"08/12/2014 21:19:48":[56.91,63.23,52.42],"07/23/2014 13:37:46": ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...

The Selenium Action class is failing to perform a second mouse hover on the same web element

Actions action = new Actions(Driver); action.MoveToElement(webelement).ClickAndHold().Perform(); The code snippet above is used to perform a mouse hover on a Web Element, and it works perfectly the first time. However, when attempting to do the mouse hove ...

Is Next.js the Ultimate Serverless Rendering Tool with Cloudflare Workers?

I am currently using Next.js version 9 and I am interested in utilizing Next's serverless deployment feature by integrating my application with Cloudflare Workers. According to the documentation for Next.js, all serverless functions created by Next f ...

I am encountering a challenge retrieving the ID via AJAX from the view to the controller. However, the ID is successfully displaying in the alert

In the view page code below, I am trying to send an ID through Ajax but it is not posting in the controller. The goal is to replace one question at a time fetching from the database. $(document).ready(function() { $("#next").click(function() { ...

Send an array using jQuery's $.post method

I am experiencing an issue with sending an array in $.post to PHP. When I use var_dump, the result is showing as "NULL" and JSON.stringify is not working. JQUERY var photobox = []; photobox.push(e.target.result); $.post("../modules/upload.php",{"imag ...

Issue with dropdown list functionality in Internet Explorer not functioning correctly

I am experiencing an issue with my dropdown lists. When selecting an item from the first dropdown list, it should not be available in the second dropdown list. To achieve this functionality, I have implemented jQuery code like the following: $(document).r ...

What is the proper way to utilize the setState() function in ReactJS?

I am new to the world of ReactJS and I have been exploring the concepts of state and setState(). While trying to implement a name change using setState(), I found myself wondering where exactly in my code should I invoke the setState() method: Should I c ...

Determine the overall sum of rows present within this particular tbody section

I am struggling to calculate the total number of tr's within my nested tbody, but I am not getting the correct count. The jQuery code I used is returning a high number like 44 rows instead of the expected 7 rows. Can anyone point out where I might ha ...

Delving into the intricacies of Promises/A+ and the mechanics of Asynchronicity in Javascript

I am new to JavaScript programming and may have some questions that seem basic. I was recently following a tutorial on Spring Boot and React. The author used a library called "rest" (package.json - "rest": "^1.3.1") and mentioned it is a Promises/A+ based ...

Embed a partial view within a Jquery modal dialogue box featuring two distinct models

I am working on a room-booking project. In my View, I have a model of rooms that displays the room ID and its characteristics using a foreach loop: @model IEnumerable<Room> <div class="roomConteiner"> @foreach (Room room in Model) ...

Key-based user retrieval is unavailable in Express, "findAll" can only be done through email

I've created a straightforward Express/Pug application designed for searching users in a database by "email" or by "key". In this setup, each user is assigned a unique string as their key. The structure of my user model and index model files can be se ...

Why is the "class" attribute of an SVG node not being applied when I change it?

I am having trouble changing the "class" attribute of a node in SVG using my AngularJS Directive. Even though I've written the code to do so, it doesn't seem to be applied properly. This is the code snippet from my Directive: node = node.data(f ...

Incorporate create-react-app with Express

Issue - I am encountering a problem where I do not receive any response from Postman when trying to access localhost:9000. Instead of getting the expected user JSON data back, I am seeing the following output: <body> <noscript>You need to ...

What is the process for obtaining a JSON file in AngularJS upon clicking a button?

Starting off with AngularJS and feeling excited. I have successfully created a form with two input boxes. Just below the input boxes, I have added: <input ng-model="id.todoList" type="text" name="input" placeholder="Enter tasks here"> <input ng ...

Reducing file size when uploading images in Angular4 through image compression

saveImage(event: any, type, image_type) { this.uploadImageFlag = true; const fileList: FileList = event.target.files; if (fileList.length > 0) { const file: File = fileList[0] this.files.set('files', file, file.name) ...

Encountering an issue with Firebase authentication in Next.js: the window object is not defined

Here is some code snippets: import { initializeApp } from "firebase/app"; import { getAnalytics } from "firebase/analytics"; import { getAuth } from "firebase/auth"; const firebaseConfig = { //credentials// }; export const ...

Transferring callback variables from an Express GET request to a forked process in Node.js

I encountered an issue while trying to transfer the callback variables from app.get() to a forked process. The error message I received was: TypeError: Converting circular structure to JSON The primary goal behind this endeavor is to enable a main node w ...

What is the process for importing something from index.js within the same directory?

My folder structure is similar to the one below /components/organisms -- ModuleA.vue -- ModuleB.vue -- index.js The content of index.js: export { default as ModuleA } from "./ModuleA.vue" export { default as ModuleB } from "./ModuleB.vue&qu ...