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);
});
}
}
添加回答
舉報