【发布时间】:2020-07-08 01:28:26
【问题描述】:
在我的组件和我的服务之下
report.component.html
<div *ngFor="let report of reports">
<p>{{report.name}}</p>
<p>{{report.value}}</p>
<p>{{report.color}}</p>
</div>
report.component.ts
export class ReportComponent implements OnInit{
reports = this.reportService.getLists('2020-03-20', '2020-03-26');
constructor(private reportService: ReportService) {}
ngOnInit(){}
}
report.service.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)上方。
更新 2
<ng-container *ngIf="reports">
<p>test</p>
<div *ngFor="let report of reports">
<p>{{report.name}}</p>
<p>{{report.value}}</p>
<p>{{report.color}}</p>
</div>
</ng-container>
模板没有显示段落“测试”......我认为变量 stats 为空
更新 3
report.component.html
<ng-container *ngIf="reports">
<p>test</p>
<div *ngFor="let report of reports">
<p>{{report.name}}</p>
<p>{{report.value}}</p>
<p>{{report.color}}</p>
</div>
</ng-container>
report.component.ts
export class SmtpComponent implements OnInit, AfterViewInit, OnDestroy {
reports:any[] = [];
}
我把reports: any;改成reports:any[] = [];
我可以显示段落“测试”, 它可能具有属性“值、名称和颜色”的初始化数组?
更新 4
this.reportService.getReport('2020-03-20', '2020-03-26').subscribe(
response => { this.lists= response; this._cdr.detectChanges()},
error => { console.log("Error")}
);
【问题讨论】:
-
请更具体。你想在哪里初始化和填充数组?以及出于什么目的?问题是在 ngFor 指令中使用报告作为数组?
标签: javascript angular typescript asynchronous promise