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.