2 回答
TA贡献1895条经验 获得超7个赞
您正在尝试进行同步调用,而该调用又会发出异步请求。那不管用。当您在调用链中的某处进行异步调用时,您需要遵循它的规则。无论您尝试如何,它都不会返回同步数据。
另一方面,您可以将异步调用的响应映射到您的格式数组。但是要检索这个数组,您仍然需要遵守异步请求的规则。
尝试以下
服务
export class ReportService {
public getReport(startDate: string, endDate: string): Observable<any> {
return this.http.get(`https://localhost:44354/report?startDate=${startDate}&endDate=${endDate}`, this.httpOptions)
.pipe(map(response => {
return
[
{ name: 'Opens', value: response.opens, color: 'green' },
{ name: 'Opens', value: response.opens, color: 'green' }
]
}));
}
}
控制器
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
export class ReportComponent implements OnInit {
reports: any
constructor(private reportService: ReportService, private _cdr: ChangeDetectorRef) { }
ngOnInit() {
// you still need to subscribe to obtain the result
this.reportService.getLists('2020-03-20', '2020-03-26').subscribe(
response => { this.reports = response },
error => { // handle error }
);
this._cdr.detectChanges();
}
}
更新
您还可以在呈现数据之前进行检查。
<ng-container *ngIf="reports">
<div *ngFor="let report of reports">
<p>{{report.name}}</p>
<p>{{report.value}}</p>
<p>{{report.color}}</p>
</div>
</ng-container>
TA贡献1799条经验 获得超9个赞
如果我使用它,我可以在日志中看到对象返回,但是为什么模板不适用于数组列表上的循环?
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);
});
}
}
添加回答
举报