首页 > 解决方案 > 如何在Angular中求和?

问题描述

ngOnInit() {
    this.homeService.readPolicies(19).subscribe((policies: Fee[]) => {
      this.fee = policies;
      console.log(this.fee);
      this.homeService.readStudent(+this.fee[0].studentId).subscribe((student: Student) => {
        this.studentfee = student;
        console.log(this.studentfee[0].fee);
        this.studentfee = this.studentfee[0].fee;
      });

});

我怎样才能做所有元素的总和?

在此处输入图像描述

标签: javascriptangular

解决方案


首先不要在订阅中订阅!使用 switchMap。当您订阅时,不要忘记取消订阅。

您可以轻松地使用 lodash 对数组值求和。

import * as _ from 'lodash'
_.sumBy(policies, 'fees');

(见https://lodash.com/docs/4.17.15#sumBy


推荐阅读