Ways in which this data can be best retrieved

Hey there, I'm currently in the process of building an Ionic2 app with Firebase integration. Within my codebase, there's a provider known as Students-services where I've written a function to navigate through a node, retrieve values, and display them in an array. While everything seems to be functioning properly, I seem to be encountering an issue when attempting to return data to my page.ts file.

Below is the snippet from students services:

settropies(userId) {
  let total = 0;
  let result = [];
  let query = this.userProfile.child(userId+'/exams/').orderByKey();

  query.on("value",(snapshot) => {
    snapshot.forEach((childSnapshot) => {
      var key = childSnapshot.key;
      var childData = childSnapshot.val();

      total = total + childData.marks;
      result.push(total);
      this.marksarray = result;  
    }); 
    this.marksarray = result;
    console.log(this.marksarray[1]);
  });
  return this.marksarray;
}

I've called the function within my page.ts file:

console.log(this.studentservice.settropies(studentId));

Answer №1

Upon your return, the array becomes undefined due to

  query.on("value",(snapshot)=> {

being an asynchronous event.

To resolve this issue, consider utilizing eventEmitter

Within your service:

   public finished$ = new EventEmitter<any>();

 snapshot.forEach((childSnapshot)=> {
        var key = childSnapshot.key;
         var childData = childSnapshot.val();
         total=total+childData.marks;
         result.push(total);
         this.marksarray=result;  
          this.finished$.emit(result);
      }); 

Then, in your page.ts file

    constructor(){

        this.studentservice.$finished.subscribe((result)=>{
            console.log(this.studentservice.settropies(studentId));

       });
    }

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

Add the file to the current directory

As a newer Angular developer, I am embarking on the task of creating a web page that enables users to upload files, with the intention of storing them in a specific folder within the working directory. The current location of the upload page component is ...

Tips for boosting ViteJs development mode performance

One issue I am facing is the slow server performance during development mode. After starting the server and opening the page in my browser, I have to wait 3–6 minutes for it to load! Initially, ViteJs downloads a small amount of resources, but then the ...

Issue with MEAN app: unable to retrieve response from GET request

FETCH The fetch request is being made but no data is returned. There are no errors, just the fetch request repeating itself. app.get('/:shortUrl',async (req,res)=>{ try{ const shortUrl = await shorturl.findOne({ short: req.params.sh ...

How to include a sub-route in Angular after adding parameters?

In this scenario: 'www.xyz.com/#/indutry/1/subIndustry/2/subSubIndustry/3' I am looking to implement this structure in my Parent route file. How can I achieve this using ForRoot? ...

Replace the function if it is specified in the object, otherwise use the default functionality

Having a calendar widget written in TypeScript, I am able to bind a listener to a separate function. However, I desire this separate function to have default functionality until someone overrides it in the config object passed to the constructor. Within th ...

Troubleshooting problem with iPhone X responsiveness

Struggling with responsive issues on iPhone X. Issue is only appearing on actual device. Any tips for fixing this? I'm facing an issue where the website looks good and responsive on all devices in Chrome's responsive view. But when I access it th ...

Troubleshooting issue in Angular 6 mat-select: original array not resetting after filtering values

When filtering an array based on multiple selections from a mat-select, everything works smoothly except for one issue - if I select an option and then deselect it, the entire array disappears from the UI. However, if I select a few other options after tha ...

What does an exclamation mark signify in Angular / Type Script?

Being a newcomer in the world of front end development, I am currently teaching myself Angular (11.2.10). While exploring a sample project, I noticed this particular piece of html template code written by another person and utilized in multiple places: < ...

Develop a TypeScript Module that consolidates all exports

My Goal with TypeScript Modules I aim to streamline my TypeScript project by creating a module that contains all the necessary class exports. Currently, I find myself using relative import statements in my classes, which can make maintenance challenging i ...

The object prototype can only be an instance of an Object or null; any other value will

While attempting to create a codesandbox in order to replicate a bug, I encountered an additional issue. You can view my codesandbox here: https://codesandbox.io/s/vue-typescript-example-o7xsv The error message states: Object prototype may only be an ...

Retrieve the canvas coordinates for the images starting at lx and ending at rx on the x-axis, and

Currently, I am working on a project where I need to implement a drag and drop feature for an image within a PDF document. The goal is to retrieve the coordinates of the dragged image and use them later for document signing. The situation I am dealing wit ...

Turn off Typescript compilation in Visual Studio for a webpage

My Angular website (not a computer science project) is integrated into a solution, causing Visual Studio 2019 to generate multiple TypeScript compilation errors while working on other projects within the same solution. You can see examples of these errors ...

Tips to avoid multiple HTTP requests being sent simultaneously

I have a collection of objects that requires triggering asynchronous requests for each object. However, I want to limit the number of simultaneous requests running at once. Additionally, it would be beneficial to have a single point of synchronization afte ...

The TN-Models-FP error message states that it is not allowed to use the `create` model without an associated `entity` model

Utilizing the TN-models-fp library to construct a basic api inspired by the provided examples, here is my implementation in api.ts: import { axios } from '../axios-instance' import { createApi } from '@thinknimble/tn-models-fp' import { ...

The specified type '{ flag: boolean; }' cannot be assigned to the type 'IntrinsicAttributes & boolean'

Just delving into TypeScript and I've hit a snag when trying to pass an element to another component. Feeling lost on how to proceed. Error lurking in Cards component export default function MySpecialProject() { const [toggle, setToggle] = useState ...

What is the process for creating a new type from a nested part of an existing type?

Currently, my website is being developed with a focus on utilizing code generation to ensure type safety when handling GraphQl queries. Certain components within the application receive a portion of an object as a prop. The specific type structure is outli ...

Serverless-offline is unable to identify the GraphQL handler as a valid function

While attempting to transition my serverless nodejs graphql api to utilize typescript, I encountered an error in which serverless indicated that the graphql handler is not recognized as a function. The following error message was generated: Error: Server ...

A step-by-step guide to activating multi-selection in the Primary SideBar of Visual Studio Code using your custom extension

Currently, I'm in the process of developing an extension for Visual Studio Code where I've added a new activityBar containing treeViews that showcase information pulled from a JSON file. My goal is to enable users to multi-select certain displaye ...

What sets [NgClass] apart from [class] in Angular JS2?

Consider a view element with the following three attributes: class="red" [class]="isGreen ? green : cyan" [ngClass]="'blue'" Does Angular merge the output of these attributes or does one override the others? If we have: [class]="getElementCla ...

Avoid altering the background color when adjusting the scale view on an apex chart due to changes in graph data

I have developed Apexchart components for line charts that come with a date filter picker feature. This chart is interactive and changes dynamically based on the series data provided. function DisplayChart({ series, xaxis }: { series: any; xaxis?: any }) ...