如何在函数onSelectedReport()
中将两个给定条件合并为一个。如果用html编写这些条件,它将看起来像这样:
html:
<div *ngFor="let report of reports">
<div *ngFor="let i of income">
<div *ngIf="report.r_income_id == i.income_id">
<div *ngFor="let c of costs">
<div *ngIf="i.i_costs_id == c.costs_id">
{{c.name}}
</div>
</div>
</div>
</div>
</div>
但是由于我需要在选定的特定标识符上显示数据,因此需要在ts上实现它。我尚未对其进行测试,但是我知道100%它将无法正常工作,因为在第二种情况下this.income.i_costs_id
的值将确定undefined
。并且这两个条件很可能应该合并为一个。该怎么办?
ts:
reports: Reports[]
income: Income[]
costs: Costs[]
selectedReport = null
filteredIncome = []
filteredСosts = []
onSelectedReport(reportId) {
this.selectedReport = this.reports.find(
el => {
return el.report_id === reportId
}
)
if (this.incomeService) {
this.incomeService.fetchAll().subscribe(
income => {
this.income = income
this.filteredIncome = this.income.filter(
(income) => income.income_id == this.selectedReport.r_income_id
)
}
)
}
if (this.costsService) {
this.costsService.fetch().subscribe(
costs => {
this.costs = costs
this.filteredСosts = this.costs.filter(
(costs) => costs.costs_id == this.income.i_costs_id
)
}
)
}
}
答案 0 :(得分:2)
尝试
reports: Reports[]
income: Income[]
costs: Costs[]
selectedReport = null
filteredIncome = []
filteredСosts = []
onSelectedReport(reportId) {
this.selectedReport = this.reports.find(
el => {
return el.report_id === reportId
}
)
if (this.incomeService) {
this.incomeService.fetchAll().subscribe(
income => {
this.income = income
this.filteredIncome = this.income.filter(
(income) => income.income_id == this.selectedReport.r_income_id
)
if (this.costsService) {
this.costsService.fetch().subscribe(
costs => {
this.costs = costs
for(let i of this.filteredIncome){
for(let c of costs){
if(c.costs_id==i.i_costs_id){
this.filteredСosts.push(c)
}
}
}
}
)
}
}
)
}
}
答案 1 :(得分:0)
您的要求符合forkJoin,我在此处添加了示例,您可以根据您的代码对其进行修改。
let requests = [];
if (this.incomeService) {
//adding income service
requests.push(this.incomeService.fetchAll());
} else {
//adding null as we must need observable of first one
requests.push(Observable.of(null))
}
if (this.costsService) {
//adding cost service
requests.push(this.costsService.fetch());
} else {
//adding null of cost
requests.push(Observable.of(null))
}
//requesting the requests
Observable.forkJoin(...requests)
.subscribe(result => {
//accessing the values
console.log(values[0], values[1]);
//check if values[0] is not null first so second one does not call too
//here values[0] is first one and values[1] is costs service call
});