Retrieving the necessary data from my object to perform a sum calculation in angular

Having trouble retrieving an attribute from an array in my code.

In my .ts file, I am fetching data from my backend endpoint like this:

export class PostFeedComponent implements OnInit {
  data: any = {};

  constructor(private http: HttpClient) { 
    this.getItems();
    this.getPosts();
  }

  getItems() {
    return this.http.get(`${environment.apiBaseUrl}/getPosts`);
  }

  getPosts () {
    this.getItems().subscribe(data => {
      console.log(data);
      this.data = data
    })
  }

  ngOnInit() {
  }

}

The console log output by the getPosts() method is as follows (from chrome console):

Object
post: Array(4)
0:
calories: 567
description: "Arroz tres delicias cocinado con salsa de soja"
eatenAt: "04/26/2019"
foodName: "Arroz tres delicias"
foodUuid: "f64718fa-a29a-4627-8744-9521133e03f0"
pictureUrl: null
_id: "5ccf85d73e4afe354d7a6b23"
__proto__: Object
1: {eatenAt: "May 6, 2019 2:57 AM", _id: "5ccf869e4f853735a4a4682b", foodUuid: "90172850-da39-4f76-a212-4dd1cb3594e3", pictureUrl: null, foodName: "Cacahuetes", …}
2: {eatenAt: "May 6, 2019", _id: "5ccf8778c9d4713602440cb9", foodUuid: "cab3a696-ef37-4dca-b088-c66c7c8cf79b", pictureUrl: null, foodName: "Azull", …}
3: {eatenAt: "May 6, 2019", _id: "5ccf8800c9d4713602440cba", foodUuid: "724c26da-51d9-426e-b2ad-bfe8665bba0a", pictureUrl: null, foodName: "patucos", …}
length: 4

My goal is to sum up the "calories" attribute in my arrays, but I'm struggling with referencing them properly in my .ts code. However, it seems to work fine when written in HTML like this:

<ng-container *ngFor="let post of data.post; let i=index;">
    <p>{{post.calories}}</p>
</ng-container>

This is the mongoose schema used in the backend:

const trackingPostSchema = new Schema({
    uuid: {
        type: String,
        unique: true,
      },
    post: [{
        foodUuid: String,
        pictureUrl: String,
        foodName: String,
        description: String,
        calories: Number,
        eatenAt: {
            type: String,
            default: date,
        },
        mealTime: String, //breakfast, lunch, dinner
    }],
  });

Here's how I send the data from Node.js:

'use strict'

const trackingPostModel = require('../../../models/tracking-post');

async function getPosts(req, res){

    const { uuid } = req.claims;

    try{
        const posts = await trackingPostModel.findOne({ uuid }, {_id: 0, __v: 0}).lean();

        return res.status(200).send(posts);
    }catch(e){
        return res.status(500).send(e.message);
    }
}

module.exports = getPosts;

The response received:

HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST,GET,PUT,DELETE,OPTIONS
Access-Control-Allow-Headers: Location,Authorization,Content-Type
Access-Control-Expose-Headers: Location,Authorization,Content-Type
Allow: GET,HEAD
Content-Type: text/html; charset=utf-8
Content-Length: 8
ETag: W/"8-ZRAf8oNBS3Bjb/SU2GYZCmbtmXg"
Date: Mon, 06 May 2019 14:45:19 GMT
Connection: keep-alive

I've tried accessing the calories using different variations like data.post.calories, data.calories, data[i].calories, data.post[i].calories and also destructuring, but without success.

Answer №1

If I assume the json structure to be similar to this:

{
 ...,
 post: [{
  calories: 123,
  ...
 }, ...]
}

One approach could be to calculate the sum of calories before subscribing using RxJs pipe operators, like so:

export class PostFeedComponent implements OnInit {
    data: any = {};

    sum: number;

    constructor(private http: HttpClient) {
    }

    getItems() {
        return this.http.get(`${environment.apiBaseUrl}/getPosts`);
    }

    getPosts () {
        this.getItems().pipe(
            tap(data => {
                // relevant part
                this.sum = data.post.map(p => {
                  return p.calories;
                }.reduce((a, b) => {
                    return a + b;
                }, 0)
            })
        ).subscribe(data => {
            console.log(data);
            this.data = data
        })
    }

    ngOnInit() {
      this.getItems();
      this.getPosts();
    }

}

By implementing this method, you will have this.sum available in your component without making any other changes.

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

Issue with data updating in Angular rxjs with share, map, and filter functions

After gathering search criteria from a form, I have developed a method that retrieves an observable of talents. fetchTalents(searchCriteria) { return this._allUsers$.pipe( tap((talents) => console.log(talents)), map((tale ...

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. ...

Angular website showing only app.component.html on the frontend

I'm currently working on developing the frontend for my API and I've encountered an issue while trying to create a new component. Despite my best efforts, including setting up an app-routing.module.ts file, my application only displays the conten ...

Datatable - pagination - retrieving data from a specific page

Can someone tell me how to retrieve the records from a specific page in a PrimeNG datatable using Angular 2.0? ...

Storing a byte array in a local file using JavaScript: A Step-by-Step Guide

Recently, I encountered an issue while working with an openssl certificate. Specifically, when I tried to download the certificate from my API, it returned byte arrays that I needed to convert to a PEM file in order to access them through another API. The ...

Angular 8 does not show the default option in the select tag

When I use the following code snippet: <div style="text-align:center"> <form> <select type="checkbox" name="vehicle1" (change)="onchange()" > <option> 1 </option> <opti ...

Dealing with observable errors in Angular 2 beta.12 and RxJS 5 beta.3

Greetings, Currently, I am working with Angular2 beta 12 within VS2015. Upon updating from rxjs version 5.0.0-beta.2 to beta.3, I started encountering several exceptions primarily related to promises. For instance: The property map is not present in th ...

Why is it necessary to omit node_modules from webpack configuration?

Check out this webpack configuration file: module.exports = { mode: "development", entry: "./src/index.ts", output: { filename: "bundle.js" }, resolve: { extensions: [".ts"] }, module: { rules: [ { test: /\.ts/ ...

Encountered an issue when attempting to create a new Angular project using the

Just starting out with Angular and encountered an issue while trying to execute this command ng new my-dream-app The error message I received was: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ER ...

Is it advisable to incorporate 'use server' into every function that retrieves confidential information within server components in Next.js?

By default, server components are enabled in Next.js 13. I'm contemplating whether I should wrap each fetch call in a separate function and include 'use server' to conceal the function's code or if it's acceptable to directly use f ...

The Angular2 Router encounters an issue with the URL when it contains the "&

Ever since updating to the latest version of angular v4.3.2, I've encountered an issue where all my URLs break at the & value. For instance, I have a route /:value from which I need to retrieve the value: http://localhost:4200/one&two Inst ...

How can I retrieve JSON data that is specific to the selected item in an Ionic Angular application?

Exploring the world of ionic-angular framework, I have a home page with a modal embedded within it. The home page displays a list of items fetched from a JSON file, and upon clicking on a specific item, I wish to display all the information related to that ...

Unable to activate parameter function until receiving "yes" confirmation from a confirmation service utilizing a Subject observable

Currently, I am working on unit tests for an Angular application using Jasmine and Karma. One of the unit tests involves opening a modal and removing an item from a tree node. Everything goes smoothly until the removeItem() function is called. This functi ...

Choosing a Component in a Collection with Angular 2

Seeking advice on how to address an issue I'm facing with a sign-up page. Within the page, there are two buttons, represented by components <btn-gender>, each displaying a gender option for selection. The challenge lies in creating a logic to d ...

Issue: "contains method is not supported" in Ionic 2

I'm currently working on a code to validate the contents of my input field, but I've encountered an issue with using the contains function. Here's the TypeScript function I have written: checkFnameFunction(name){ if(name.contains("[a-z ...

How to send parameters with the fetch API

After completing a task that involved converting code from Angular HttpClient to using fetch API, I encountered an issue with passing parameters. Below is the original code snippet before my modifications: let activeUrl = new URL(this.serverAddress); ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

Using Firebase: retrieving getAdditionalUserInfo in onCreate of a Firebase Cloud function

Can anyone help me figure out how to retrieve extra data from a SAML login provider in the backend (firebase functions)? I can see the data on the client side but I'm struggling to access it in the backend. I've specified these dependencies for ...

Is it possible to use Angular CLI 6 to run ng serve with Angular 4?

I have a project using Angular 4. I recently updated my Angular CLI version: Angular CLI: 6.1.5 Node: 10.9.0 OS: win32 x64 Now I'm wondering how to run ng serve for my Angular 4 project? However, I noticed that the file angular.json is missing in ...

Using RXJS with the 'never' subject as the specified generic type

In my current Angular project, I am using RXJS and Typescript. The code snippet below shows what I have implemented: const sub = new Subject<never>(); My understanding is that the above line implies that any subscriber defining the 'next' ...