Using AngularJS to retrieve a string array from data stored in Angular Firestore by invoking a function

As a newcomer to Angular, I am attempting to retrieve details from Firebase as a string array using the function below:

Firestore : companies > details > app > name: "WM,TT,MP"

getCompanies(): string [] {
var appl: string []  = [] ;

this.db.database.ref("companies/details/app/").on('value', function (snap) {

  snap.val().name.split(",").forEach(function(x:string){
    appl.push(x);
    console.log(">>>first "+appl.length);
  });

  });

  console.log("Reached here ");
  console.log(">>>second "+appl.length);
  return appl;
}

Upon invoking getCompanies in a component during initialization like this:

 ngOnInit() {

    console.log(">>>"+this.localservice.getCompanies().length);


  }

While there are no errors, the output is not as expected. The string array is returning empty, with the length being blank.

Reached here 
>>>second 0
>>>0
>>>first 1
>>>first 2
>>>first 3

The issue seems to be that the second step is executing before the first step, resulting in an empty string array. How can this be resolved in Angular?

Answer №1

The issue of logging and returning the appl outside the callback function is causing the second log to appear before the first one.

To solve this problem, you should move the logging and return for appl inside the callback function like this:

getCompanies(): string [] {
var appl: string []  = [] ;

this.db.database.ref("companies/details/app/").on('value', function (snap) {
  snap.val().name.split(",").forEach(function(x:string){
    appl.push(x);
    console.log(">>>first "+appl.length);
  });

       console.log("Reached here ");
       console.log(">>>second "+appl.length);

       return appl;

 });

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

The Angular data table is encountering an issue as the dataStream.pipe function is not recognized

I'm currently working on setting up a table using Angular data table, but I've run into an issue related to the dataSource. I'm seeing an error message that says "dataStream.pipe is not a function", and I'm having trouble resolving it. ...

"Integrating FullCalendar with Cloud Firestore for seamless data management

Is It Possible to Integrate Observable with FullCalendar? I have a collection in Cloud Firestore and I want to display the data from this collection in real-time on FullCalendar. Although I know that using an Observable is necessary for this task, it see ...

Error encountered while trying to create a new project using Angular-

After executing ng new onepage, I encountered the following error message after waiting for a few minutes: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8b9e8d8f898a9980c18a9facddc2dec2df">[email  ...

Utilizing Angular's custom builder for asset revisioning

After coming across this specific inquiry on Stack Overflow, my goal is to implement a @angular-builders/custom-webpack:browser with a personalized Webpack setup that incorporates html-loader and file-loader to alter the names of asset files with their has ...

How can I update a dropdown menu depending on the selection made in another dropdown using Angular

I am trying to dynamically change the options in one dropdown based on the selection made in another dropdown. ts.file Countries: Array<any> = [ { name: '1st of the month', states: [ {name: '16th of the month&apos ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

Ways to obtain the present value in Angular

Hello, I am looking for assistance in displaying Toast notifications on my View whenever the number of notifications increases (i.e., when new data is added to the database). I have attempted to use this function, but I am unsure how to retrieve the curre ...

Select hours using the PrimeNG slider feature

Is there a way to customize the PrimeNG slider in order to allow for selecting a time interval? I would like the slider to default to 12:00 when the user opens the application, but also be able to extend the selection range from 00:00 to 23:59. It seems ...

Creating key elements in JavaScript with the push() function

I'm working on a basic shopping cart system using JavaScript (Ionic 2 / Angular). In my PHP code, I have the following: <?php $cart = array( 48131 => array( 'size' => 'STANDARD', 'qty' => ...

Can Angular Interpolation be utilized to showcase Angular components?

I am currently working with an Angular component that relies on a getData method to display results using Angular interpolation in its template. However, I have encountered a scenario where I need a child component to override this method and return a cust ...

When trying to click on the submit button in Angular forms, it fails to work

I'm encountering an issue with Angular forms when updating data. Despite the backend update method working fine, the submit button fails to trigger the data update. Can you help me spot the mistake in my code? Take a look at my Angular component HTML ...

Encountered an issue while setting up an object variable: Error - **'const' declarations must be initialized.**

When attempting to initialize an object and assign a value to it, I encountered an error while declaring the object. Error: 'const' declarations must be initialized. How can I properly initialize my object? Code: // Object export type DateRan ...

Steps for dynamically adding a link to images in React with TypeScript based on a condition

In my project, I am looking to dynamically add links to images based on certain conditions using JavaScript and React. Here's what I aim to achieve: I have separate mobile and desktop images in my application. Under the mobile image, there is a text ...

Encountering an issue of THREE.EventDispatcher being undefined while trying to create a THREE.OrbitControls instance using THREE.js, THREE.OrbitControls, and TypeScript

Attempting to delve into typescript alongside three.js, I've encountered a perplexing error that has me stumped. The root of the issue lies within the init function where I initialize a new THREE.OrbitControls controller. Utilizing the setup provided ...

Converting a Promise to an Observable in Angular using Typescript

I have a working method that functions as intended: getdata(): Promise<any> { let query = `SELECT * FROM table`; return new Promise((resolve, reject) => { this.db.query(query, (error, rows) => { if(error) reject(error); ...

The name 'withStyles' is nowhere to be found

import * as React from "react"; import Button from "@material-ui/core/Button"; import * as PropTypes from "prop-types"; import {WithStyles} from '@material-ui/core'; import "./App.css"; import PageTwo from "./components/PageTwo"; ...

Please indicate the Extended class type in the return of the child Class method using TypeScript 2.4

I'm currently in the process of upgrading from TypeScript version 2.3.2 to 2.4.2. In the previous version (2.3), this piece of code functioned without any issues: class Records { public save(): Records { return this; } } class User extends ...

What could be causing issues with my Angular and Express.js Server-Sent Events implementation?

Objective: Implement Server-Sent Events in Angular App with Express Backend Issue: Client does not receive Server-Sent Events Backend Implementation router.get('/options/:a/:b/:c', async (req, res) => { console.log('options endpoint c ...

Guide on setting up redux store from server component using next.js and app router

I'm currently working with Next.js 13, React, and Redux to handle state management. My main objective is to fetch initial data on the server side and present it on the client side. Although I assumed this would be a typical approach with Redux and Ne ...

Adjust the control's value as you monitor any modifications

As I monitor the changes within a reactive form by subscribing to the value changes, I have encountered an issue where certain values unset in the form prevent the Angular Material Slide Toggle from toggling to false. This is crucial as it affects the "Act ...