Issue with Angular causing empty array return from [].concat.apply function

In my Ionic code snippet, I have the following function defined in a factory:

.factory('resultsFactory', function($http, $q, $rootScope, $firebaseArray, $timeout) { 
  var results = {};  

  function _all(){
    var d = $q.defer();
    var palabras =  $rootScope.textAreaOfrecer.toLowerCase().split(' ');
    var solicitudes = [];
    Promise.all(
              solicitudes = palabras.map(palabra => $firebaseArray(firebase.database().ref().child("solCompras").orderByChild("palabras/" 
                                               + palabra).equalTo(true) ) )
                     );

    var array = [].concat.apply([],solicitudes);

    d.resolve(array);

    return d.promise;       
  }

  results.all = _all;
  return results;
})

However, when executing the line of code:

var array = [].concat.apply([],solicitudes);
, it's returning an empty array.

https://i.sstatic.net/YtsXM.png

Answer №1

By utilizing the method [].concat.apply(solicitudes) in place of the current one. In case the array palabras is empty, then [].map(...) == [] could simply return Promise.all(solicitudes) directly.

function _all() {
        var palabras = $rootScope.textAreaOfrecer.toLowerCase().split(' ');
        return Promise.all(palabras.map((palabra) => {
            return $firebaseArray(firebase.database().ref().child("solCompras").orderByChild("palabras/" + palabra).equalTo(true));
        }));
    }

Answer №2

$scope.requests = [{post: 'Loading..'}];


Promise.all(
      $scope.requests = words.map(word => $firebaseArray(firebase.database().ref().child("solPurchases").orderByChild("words/" + word
                                                   ).equalTo(true) ) )
             ).then( function (){
                               //https://www.jstips.com/en/flattening-multidimensional-arrays-in-javascript/
                               var newArray = $scope.requests.reduce(function(prev, curr) {
                                 return prev.concat(curr);
                               });

                               $scope.requests = newArray;
                         });

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

Using Discord.js to filter messages that start with a specific phrase and finding a solution for handling DiscordAPIError when using bulk

This is the code I am currently using. Shout out to @André Dion for the assistance. if (message.channel.type == 'text') { message.channel.fetchMessages().then(messages => { const botMessages = messages.filter(msg => msg.auth ...

Utilize CSS appropriately for various web browsers

Embarking on my web development journey. Currently working with a CSS snippet that looks like this: height: calc(100vh - 46px); This code is effective across most browsers, but for Mozilla, height: -moz-calc(100vh -46px ); It seems to work. However, I ...

The instance does not define the property or method "message" but it is being referenced during rendering

** Check out the Screenshot Below:-** https://i.sstatic.net/u2UeW.png Take a look at MessageComposer.vue:- <template> <div class="composer"> <textarea v-model="message" @keydown.enter="send" placeholder="Message..."></textare ...

Getting values from check boxes with the same name in a POST request utilizing Node - the ultimate guide!

As a newcomer to the Node language, I am facing issues trying to retrieve the values of checkboxes with the name 'hobbies[]' from the req.body object. The contents of req.body are as follows: { title: 'Ume', gender: 'female&apos ...

Is it possible to send an ajax request within another ajax request?

I'm facing an issue with a php file that is sending an ajax request to another file located on a different domain name. The receiving parser then processes the information and sends it via ajax to yet another php file where the final action is carried ...

What are the essential files required to begin with d3.js?

Starting off with d3.js, I've downloaded the newest version from https://github.com/dc-js/dc.js/releases. Along with the d3.js file, there are plenty of other scripts located in the src and spec directories. Is it necessary to move all of these files ...

Encountering a parsererror with $.ajax while processing JSON that includes a new Date() object

After fetching JSON from a MongoDB database, I serialize it and send it back to the JavaScript client using a $.ajax call. Here is an example of the $.ajax call: function server_request(URL, httpMethod, dataObject) { var output = ""; var typeofD ...

Convert a JSON string to Unicode and then parse it back into its original format

I am currently facing a challenge with dumping a Unicode string containing JSON to the value of another JSON, passing it as a JSON response to an API, and then parsing it back. While this may seem simple, I have encountered some difficulties in the process ...

``I am facing an issue where Angular fails to update a $scope variable after

I am experiencing an issue with my AngularJS script. I have created a website for my personal network where I can control bulbs. I access the site on both my computer and mobile device. When I turn on a bulb on my mobile phone, the light goes off. I can ...

Determining the latest date within a multi-faceted attribute

Incorporating Angular $http, I have successfully retrieved a model from a database. This model consists of a Forum object with various Topics, each containing multiple Posts. My current task involves creating a grid to display |Topic Description|Count of ...

What could be the reason for the onclick event not being rendered in Bootstrap-Vue

I am facing an issue with a bootstrap-vue b-button that has a v-on:click tag. The problem is that the onclick event is not appearing in the rendered HTML. Here are the dependencies being used: "webpack": "^5.35.1", "webpack-cli&quo ...

Getting into particular fields of an embedded object array using a dynamic variable in Meteor: a step-by-step guide

Users have defined an array of strings with different combinations: pickedStrings = ["A", "B", "G", "L", "Y"]; This can also be: pickedStrings = ["A", "G"] or pickedStrings = ["A", "L", "Y"] or any other mix. More strings may be added in the future. ...

Animating the smooth collapse of panels within listviews

I have successfully implemented a smooth animation code for a collapsible panel, and it is working wonderfully: <script type="text/javascript"> function pageLoad(sender, args) { smoothAnimation(); } function smoothAnimation() ...

Change the field of view (FOV) of the Three.js camera according to

Is there a way to modify the standard Three.js resize code so that the scene scales with the DOM element's width as it does with the height? Currently, the scene scales in relation to the element's height, but when the width decreases, the model ...

Using a local function within Node.js and referencing it with the <%%> tag in a document

I am currently working with Node.js and attempting to utilize a local function within a document that requires the JSON I send in the res.render. Is there a method to achieve this? Below is an example of how I attempted to implement it: <%local_vari ...

A stateless component in React must always return a valid React element or null

I am a beginner with ReactJS and I am facing an issue. My goal is to showcase Hello world using the code snippet provided below, however, I keep encountering this error message: Can someone guide me on what I might be overlooking? The following is the c ...

Exploring the Matrix Filter Functionality in JavaScript

After successfully setting up CSS rotation for all browsers, I am now looking to achieve the same effect using JavaScript. jQuery is also being utilized in this process with the following code snippet: .css({ '-ms-filter':"progid:DXImageTransfor ...

Angular2 - How to track or listen for (click) events on dynamically inserted HTML elements

I'm trying to inject a string with a dynamically retrieved (click) event into an Angular2 template. Since this string is fetched from the back-end after the DOM is loaded, Angular doesn't recognize the injected event. Here's an example of t ...

Exploring the process of filtering multiple fields in React JS

I currently have an array containing 1000 objects with various properties, including "company," "owner," and "city." { "company": "Seattle Sutton", "owner": "Gartling", "city": "Des Moines" ...

Upon choosing a value from the DropDownList for the second time, it appears that the newly selected value is not being utilized. Instead, the old values are being retained

One of my divs is named "ddlFiles" and it contains a DropDownList with various id's. My goal is to have a user select an id, then trigger an operation by passing in the selected value (which is required by a stored procedure). The operation works the ...