Angular 从服务加载数组后如何调用函数?不同时
My ionic angular app主页使用“ionViewWillEnter”显示数组值“amount”的总和 除了在初始加载时属性“totalExpenses”默认值为0外,这一切正常 “ionViewWillEnter”正在工作并输出到控制台,但只有当我离开并返回主页时,计算才会显示正确的结果 为什么会这样?我怀疑是在填充数组之前获取数组值的总和 My.ts文件:Angular 从服务加载数组后如何调用函数?不同时,angular,typescript,ionic-framework,Angular,Typescript,Ionic Framework,My ionic angular app主页使用“ionViewWillEnter”显示数组值“amount”的总和 除了在初始加载时属性“totalExpenses”默认值为0外,这一切正常 “ionViewWillEnter”正在工作并输出到控制台,但只有当我离开并返回主页时,计算才会显示正确的结果 为什么会这样?我怀疑是在填充数组之前获取数组值的总和 My.ts文件: import { Component, OnDestroy, OnInit } from "@angular/c
import { Component, OnDestroy, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { NavController } from "@ionic/angular";
import { Subscription } from 'rxjs';
import { ExpensedataService } from "../expensedata.service";
import { Expenseitem } from "../expenseitem.model";
@Component({
selector: "app-receipts",
templateUrl: "./receipts.page.html",
styleUrls: ["./receipts.page.scss"],
})
export class ReceiptsPage implements OnInit, OnDestroy {
loadedExpenses: Expenseitem[];
private expensesSub: Subscription;
totalExpenses: number = 0;
constructor(
private expensedataService: ExpensedataService,
private route: ActivatedRoute,
private navCtrl: NavController
) {}
ngOnInit() {
this.expensesSub = this.expensedataService.expenseitems.subscribe(expenseitems => {
this.loadedExpenses = expenseitems;
});
}
ionViewWillEnter() {
this.expensedataService.fetchExpenseitems().subscribe();
this.calcTotal();
}
calcTotal() {
let expenseTotal = 0;
for (let i of this.loadedExpenses) {
expenseTotal += i.amount;
}
this.totalExpenses = expenseTotal;
console.log("calcTotal: " + expenseTotal);
}
ngOnDestroy() {
if (this.expensesSub) {
this.expensesSub.unsubscribe();
}
}
}
在响应到达之前调用函数,因此loadedExpenses为空。 请始终记住,请求是异步的
ngOnInit() {
this.expensesSub = this.expensedataService.expenseitems.subscribe(expenseitems => {
this.loadedExpenses = expenseitems;
this.calcTotal(); // move to here
});
}
在响应到达之前调用函数,因此loadedExpenses为空。 请始终记住,请求是异步的
ngOnInit() {
this.expensesSub = this.expensedataService.expenseitems.subscribe(expenseitems => {
this.loadedExpenses = expenseitems;
this.calcTotal(); // move to here
});
}
你好你能用这个问题制作一个stackblitz演示吗?如果你愿意,你可以用叉子叉;)你好你能用这个问题制作一个stackblitz演示吗?如果你愿意,你可以用叉子叉;)太棒了,谢谢!我已经尝试过将函数放在括号外的ngOnInIt()中,但没有成功,因为我现在知道它是异步运行的!太棒了,谢谢!我已经尝试过将函数放在括号外的ngOnInIt()中,但没有成功,因为我现在知道它是异步运行的!