从我的对象中获取正确的数据,以角度

时间:2019-05-06 12:31:16

标签: angular typescript

我正在尝试从拥有的数组中获取属性,但似乎无法做到这一点。

在我的.ts档案中,我正在调用后端端点并获取以下数据:

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() {
  }

}

我在getPosts()方法中拥有的控制台日志返回以下内容:(从我的chrome控制台)

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

所以我想做的是访问数组中的“卡路里”属性,并将它们加起来以获得总卡路里,但是,我不知道如何在我的.ts代码中引用它们。当我在html中这样写时,它可以工作:

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

我从后端调用的猫鼬模式:

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
    }],
  });

我是从这样的节点发送它的:

'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;

我得到的答复:

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

我尝试使用data.post.calories,data.calories,data [i] .calories,data.post [i] .calories ...等。破坏也是如此,但我无法抓住它:/

1 个答案:

答案 0 :(得分:0)

假设我希望您的json是这样的

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

您可以尝试在订阅前使用RxJs管道运算符直接获取卡路里的总和,类似

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();
    }

}

,您将在组件内设置this.sum,而无需进行其他任何修改