在我的组件和我的服务下方
报告.component.html
<div *ngFor="let report of reports">
<p>{{report.name}}</p>
<p>{{report.value}}</p>
<p>{{report.color}}</p>
</div>
报告.component.ts
export class ReportComponent implements OnInit{
reports = this.reportService.getLists('2020-03-20', '2020-03-26');
constructor(private reportService: ReportService) {}
ngOnInit(){}
}
报告服务.ts
export class ReportService {
async getLists(startDate: string, endDate: string) {
this.getReport('2020-03-20', '2020-03-26').then(response => {
let lists = [
{
name: 'Opens',
value: response .opens, //2
color: 'green',
},
{
name: 'Closes',
value: response .opens, //1
color: 'red',
}];
return lists;
});
}
async getReport(startDate: string, endDate: string) {
return await this.http
.get<Report>(
`https://localhost:44354/report?startDate=${startDate}&endDate=${endDate}`,
this.httpOptions
)
.toPromise();
}
}
可以初始化和填充数组列表吗?
我想在我的模板中使用 ngFor 循环,
我不知道我是在组件还是服务中初始化数组。什么是最好的解决方案?
更新
export class ReportComponent implements OnInit {
reports: any;
constructor(private reportService: ReportService) { }
ngOnInit() {
// you still need to subscribe to obtain the result
this.reportService.getLists('2020-03-20', '2020-03-26').subscribe(
response => {
this.reports = response;
console.log(this.reports);
});
}
}
我测试了你的答案,但是它不起作用,我只是尝试用值初始化我的数组,我的模板上有结果
所以我认为,init数组不好..
我只想使用报告对象从数组 List 初始化属性值,例如 this.list[0].value = report.opens 我不知道它是否清楚....
输出
(2) […]
0: {…}
name:"Opens"
value: 2
color:"green"
<prototype>: Object { … }
1: {…}
name:"Closes"
value: 1
color: "red"
<prototype>: Object { … }
length: 2
<prototype>: Array []
在组件中的 console.log(this.report) 上方。
人到中年有点甜
扬帆大鱼
相关分类