Promises do not yield an array of objects

I am currently working on a project that involves using AngularJS with Firebase. In order to retrieve data from Firebase, I have implemented the following code snippets.

Controller.js

$scope.load_msg=function(){
  $scope.msg=[];
  Chat.load_msg($scope.name,$scope.user.profile.name).then(function(arr){
    $scope.msg=arr;
    console.log($scope.msg);
  },function(error){
    console.log(error);
  });
}

Service.js

load_msg:function(name,frm){
  var deferred = $q.defer();
  var sref=ref.child('/Chats/'+frm);
  var rref=ref.child('Chats/'+name);
  var msgArray=[];
  ref.orderByChild("to").equalTo(name).once('child_added',function(messages){
    msgArray=msgArray.concat(messages.val());
    deferred.resolve(msgArray);
  },function(error){
    deferred.reject(error);
  });
return deferred.promise;
}

Although the msgArray successfully retrieves all elements queried by on(), only the first object is stored in arr in the controller. How can I pass the entire array msgArray through the promise?

Answer №1

The issue lies within this section:

load_msg:function(name,frm){
  var msgArray=[]; //Every time the function is called, the array gets reset.
  ref.orderByChild("to").equalTo(name).once('child_added',function(messages){
    msgArray=msgArray.concat(messages.val());
    deferred.resolve(msgArray);
  });
return deferred.promise;
}

To resolve this problem, consider implementing the following changes:

ServiceFunction() {
  var msgArray = [];
  return {
    load_msg:function(name,frm){
  ref.orderByChild("to").equalTo(name).once('child_added',function(messages){
      msgArray=msgArray.concat(messages.val());
      //Include deferred resolve logic here...
    });
  }
}

Answer №2

Using the .once('child_added' method means it will only trigger once, specifically for the first child item.

If you want continuous updates, consider using on('child_added' or once('value'. In this case, since you named your parameters messages, it's likely you are interested in the latter option:

ref.orderByChild("to").equalTo(name).once('value',function(messages){
  messages.forEach(function(message) {
    msgArray.push(message.val());
  });
  deferred.resolve(msgArray);
},function(error){
  deferred.reject(error);
});

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

Tips for passing several parameters through an AJAX POST call in Yii2 framework

My view consists of a detailview and a gridview. The grid view has check-boxes for all the columns, while the detail view contains the model id. What I need is to select a column from the grid view, and upon clicking on an a link button, send an ajax call ...

Restricting Checkbox Choices with JavaScript by Leveraging the forEach Function

I am developing a checklist application that limits the user to selecting a maximum of three checkboxes. I have implemented a function to prevent users from checking more than three boxes, but it is not working as expected. The function detects when an ite ...

What is the significance of the "rc" within the version structure of an npm package?

Can someone help me understand what the rc in 2.2.0-rc.0 signifies? I'm curious if it indicates that this version is ready for production use. ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...

How to submit a form using AngularJS on an ASP.NET webpage

Having some frustrations with asp.net... I have a basic website with a form in my master page that needs to be server-side because of the controls I use. Now, I want to incorporate angularjs into a simple page on this site. My goal is to only submit the fo ...

Struggling to access a property within an object in my Angular controller

Currently, I am utilizing a factory method to extract information about a television show from a database. However, I am encountering difficulties when attempting to send only the episodes field of this object to an angular service. Despite my efforts with ...

Guide on retrieving the response headers with jQuery and AJAX

Connection: keep-alive Content-Length: 2231 Content-Type: text/html; charset=utf-8 Date: Thu, 13 Sep 2018 07:37:46 GMT ETag: W/"8b7-XOXhf04O/VM7yxWQ561PEgxRfz8" x-auth: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YjlhMGEyM2Q0NmI3YjFmYTQzNWI ...

Navigating to an Element in React's Document Object Model

Using React 16.4, I am faced with the need to scroll to a specific DOM element within the application. Since refs are deprecated in React, I am on a quest to find the most elegant solution for this problem. However, I find it challenging to come up with a ...

Experiencing Issues in Building with React Firebase Hooks and Vite

While attempting to compile my react project using vite, I encountered the following error message. node_modules/react-firebase-hooks/auth/dist/auth/types.d.ts:2:50 - error TS2304: Cannot find name 'AuthActionHook'. 2 export declare type EmailA ...

Processing JSON in PHP after an AJAX POST request

In the scenario where JavaScript is used to make an ajax request: index.js- var dataFeedback = $("#feedback_popup_message_body").val(); var jsonObj = JSON.stringify({dataFeedback: dataFeedback}); $.ajax({ url: "index.php", type: 'POST' ...

Traverse the initial three elements of an array using JavaScript (React)

Let's say we have a collection of 5 items: const items = [ {id: 1, name: 'book', price: 50}, {id: 2, name: 'phone', price: 450}, {id: 3, name: 'fish', price: 80}, {id: 4, name: 'apple', price: 5}, {id: 5, name: ...

How to ensure that the iframe is completely loaded before proceeding with Selenium JavaScript

I have a webpage that displays an iframe, within the iframe there is a spinning spinner (overlying the fields). My approach involves using selenium to navigate to the iframe, return this.driver.wait(function() { return self.webdriver.until.ableToSw ...

Exploring the Dynamic Styling Power of Angular's ng-class Directive Alongside the Transition from

I recently updated my app from Fontawesome version 4 to 5 by following the guidelines provided HERE. Everything looks great and appears to be working smoothly, except for the dynamic icons... In my Angular-based app, the icon to display is often dynamic: ...

Encountering a module injection error in AngularJS related to the ui.grid feature during my first experience with it

Trying to develop an AngularJS app, encountering the following error upon running the code: Uncaught Error: [$injector:modulerr] Failed to create module myApp: Error: [$injector:modulerr] Failed to create module ui.grid: Error: [$injector:nomod] Module &a ...

Get the maximum width in pixels through JavaScript when it is specified in different units within the CSS

I'm looking to retrieve the max-width value in px from CSS for use in a JavaScript code. The challenge is that this value might be specified in different units in the CSS file. Any suggestions on how to achieve this using JavaScript? const element = ...

Is there a way to tally the frequency of a specific property appearing in one array within another, and then transfer those matches into a separate array?

My goal is to match the fk_city with the $id of each city in the 'list_cities' array, and then calculate the number of occurrences. const list_cities = [ { $id: '15FG', name: 'Pittsburg' }, { $id: '50HS', name: & ...

Embed a Link Fill Script into an Input Form

I have a program that automatically inserts specific links into an input form when clicked. However, I am encountering a problem. For some reason, I instructed the links to use the class linkText and specified certain values to be shown in the input text ...

What is the process for determining the text direction of a website's title?

My website is having trouble displaying the title in the correct direction. I've attempted to add dir="rtl" to various tags like html, head, and title, but nothing seems to be working. In the English version I have "Select a service:" In the Arabic ...

What steps can I take to resolve the issue of encountering the error message "Module '@endb/sqlite' not found"?

Currently, I am facing a challenge while attempting to set up a database for my discord bot using node.js with sql/sqlite 3. I have installed the necessary dependencies such as 'endb', sql, and sqlite3 through npm install. However, upon completio ...

What is the proper way to invoke the function located within a jQuery plugin?

I have incorporated a jquery plugin called vTicker on my webpage for automatic vertical news scrolling. This plugin, available from this link, works seamlessly with an rss jquery plugin. The integration is successful, but I now have a requirement to add a ...