Using Angular's For Each loop to send a post request

Struggling with sending a post request in Angular using angular.forEach loop and resolving promise with $q.all()...

This is my current setup:

angular.module('dataApp')
  .factory('UserService', function () {
    var User = $resource(ENV.API_URL + '/user/:email', {
      email: '@email'
    }, {
      add: {
        method: 'POST',
        url: ENV.API_URL + '/user/:email/medication/:medicationId',
        params: {
          email: '@email',
          dataId: '@medicationId'
        }
      }
    });

    User.addData = function (dataList) {
      var promiseArray = [];

      angular.forEach(dataList, function (data) {

        User.add({
          email: currentUser.email,
          dataId: data._id
        }).$promise.then(function success(response) {
          promiseArray.push(response.$promise);
        }, function error(response) {
          promiseArray.push(response.$promise);
          promiseArray.push(response.$promise);
        });
      });

      return $q.all(promiseArray);
    };
  });

Encountering an issue where the promises pushed into promiseArray turn out to be empty quotes (e.g. console.log(promiseArray) ==> ["", ""]). Any idea what might be missing here?

Answer №1

What is the reasoning behind utilizing the add method? In scenarios like this, there is also an option to use the save method.

Nevertheless, you could experiment with the following code snippet:

promiseArray.push(User.add({
                      email: currentUser.email,
                      dataId: data._id
                 }).$promise);

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

Limiting jQuery datepicker to only show the selected date and disabling all others

I have two datepickers named startdate and enddate. My goal is to restrict all other dates in the enddate datepicker except the selected date from the startdate datepicker. For instance, if I choose 15/12/2016 from the startdate datepicker, I only want the ...

React has been reported to display a Minified React error even in its development mode

Currently, I am utilizing browserify and babel for transpiling and bundling my script. However, a challenge arises when React 16 is incorporated as it presents the following error message: Uncaught Error: Minified React error #200; for more details, kin ...

Can the hexadecimal code for a particular color name be identified?

Similar Question: Javascript function to convert color names to hex codes Is there a way to determine the hexadecimal value of a named color that is currently being used by the browser? For example, I would like to achieve something similar ...

Is it possible to combine callbacks and promises in node.js, or must one be chosen over the other?

I am just starting to delve into the realm of NodeJs. After perusing through this insightful article, a question came to mind: Can callbacks and promises be interchanged, or are they fundamentally different? My efforts to find a definitive answer have ...

What steps can I take to incorporate a user-controlled autoscroll feature into this Carousel?

I am in the process of creating a "slideshow" using text boxes that can be scrolled with arrow buttons. My goal is to have the slideshow automatically scroll only until the user interacts by clicking one of the arrow buttons. Below is the state logic re ...

Customize the border style for the span element

I attempted to use the code below in JavaScript/jQuery to adjust the border thickness. Unfortunately, it seems to be ineffective. Can someone please assist me? //$("span").css({"border":"4px solid green"}); document.getElementById("192.168.42.151:8984_ ...

Unlock the ability to retrieve the context element from a dynamically bound event within the event handler using jQuery

I have a chunk of HTML that gets inserted into the page and is connected to a click event handler. Here's an example in the code snippet below: var matchMore = $(".match-more-btn"); matchList.on("click", matchMore, function() { var self = $(this); ...

Tiny adjustment to jQuery Collapsible Panel

I have successfully implemented a jQuery Accordion in my demo. When I click on 'About Us', it reveals the 'Team' link below. Exciting! Now, I am wondering if it is possible for this Accordion to function without needing the 'item& ...

Using JavaScript to execute a JSON parse function will not work

I am currently working on this code and would appreciate any assistance. I'm trying to retrieve and parse data from my listApp.json file to display a list with one link. As a beginner, I could use some guidance. <script type = "text/javascript"> ...

Dialogue box closes automatically within a dropdown menu

I am using shadcn in my next.js 13 project and I want to implement a dropdown feature that allows users to edit or delete an entry. However, when the user clicks on "delete", the dialog pops up for only about 0.5 seconds before closing along with the dropd ...

Leveraging JavaScript for Triggering an Infinite Loop of 1 GET and 2 POST Requests

I don't have much experience with JavaScript, but I believe this can be achieved. I require the script to perform 3 tasks: Make a GET request to https://example.com/test.php which will return this JSON: [{"user_id":"12345","email":"<a href="/ ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

Developing a node.js application with express that effectively manages synchronous function calls and value passing in a modularized structure

I am currently developing a node.js/express application to validate user account details in order to determine their eligibility to access a specific resource. Initially, all the code was housed in a single app.js file, but now I am restructuring it into m ...

Using JQuery to showcase JSON data

Struggling with showcasing nested objects from a JSON structure on a webpage using JQuery's .getJSON function. The code snippet with the JSON data is as follows: { "widget": { "debug": "on", "window": { "title": "Sample Konfabulator W ...

Spotlight barn doors in Three.js are an innovative feature that

I have been experimenting with three.js to build a scene featuring spotlights. Is there a way to achieve the barn door effect for the lights in three.js? I attempted using small cubes as barn doors to block the light, but it was not successful. I am look ...

JavaScript facing issue with $.get command executing in incorrect order

I have encountered an issue with my JavaScript code where it is not running in sequence. The script includes an unload function that uses the $.get jQuery command to fetch a file, which is then supposed to be printed to an external device. To debug this ...

The async task in Gulp version 4 seems to be hanging and not completing its

Currently, I'm in the process of transitioning my tasks to functions while working with v4 gulp. One of the tasks involves implementing a simple clean function that executes a parallel task. const clean_server = () => del('build/server/*&apos ...

When scrolling through videos in Chrome and Firefox, frames are lost once the resolution surpasses a certain level

Although it may seem like a straightforward issue, all attempts with various encodings have failed to resolve it. The issue involves the page adjusting the currentTime of the video based on the position of the scroll bar: Does anyone have insights into w ...

How can I retrieve the class of the parent element by referencing the child id in jQuery?

I want to trigger an alert on click from the child id <th id="first"> to the table(parent) class. alert($(this).parent('tr').attr('class')); This code helped me to get the class of the <tr>. However, when I try to get the ...

Is Webpack bundling the node_modules of node_modules into the bundle?

Recently, I noticed that webpack is bundling dependencies from the top-level node_modules directory into my actual bundle. For instance, one of my dependencies, example-dep, relies on lodash and has a nested node_modules directory at node_modules/example-d ...