Angular模板展示HTTP请求数组求和结果失败,求解决方案
问题解决方法
核心问题分析
你代码里的问题主要有两个:
- 计算出的
total没有赋值给组件的result变量,HTML模板绑定的result始终是空值 getSumFacture方法可能没有被触发执行
修改后的TS代码
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-your-component', // 替换成你的组件选择器 templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit { result: number = 0; // 明确类型为数字,初始值设为0 products: any[] = []; // 声明products数组 url = '你的接口地址'; // 替换成实际的接口URL constructor(private http: HttpClient) { } ngOnInit(): void { this.getSumFacture(); // 在组件初始化时调用方法 } getSumFacture() { this.http.get<any[]>(this.url).subscribe((data: any[]) => { this.products = data; // 确保totalPrice转成数字,避免字符串拼接问题 this.result = this.products.reduce((sum: number, current: { totalPrice: number | string }) => { return sum + Number(current.totalPrice); }, 0); console.log(this.result); // 此时控制台输出的就是最终总和 }); } }
关键修改点
- 在
ngOnInit中调用getSumFacture,保证组件加载时触发HTTP请求 - 将计算后的总和赋值给
this.result,这样HTML模板才能获取到值 - 用
Number()转换current.totalPrice,防止接口返回的是字符串类型导致错误的拼接结果 - 给
result和products声明明确的类型和初始值,避免undefined问题
HTML模板保持不变
{{ result }}
内容的提问来源于stack exchange,提问作者Juan felipe Arias tabares
相关产品推荐
相关产品推荐

