我已经为API调用编写了一个服务来获取数据。以下是我的服务代码。
export class SurveyServiceService {
private surveysUrl =
'http://107.170.59.79/services/public/api/v1/countries';
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http) { }
getSurveys(): Promise<Survey[]> {
return this.http.get(this.surveysUrl)
.toPromise()
.then(response => response.json() as Survey[])
.catch(this.handleError);
}
}
以下是我的getSurveys功能组件
export class SurveysComponent implements OnInit {
title = 'Survey List';
surveys: Survey[];
keys: String[];
selectedSurvey: Survey;
constructor(private router: Router,
private surveyService: SurveyServiceService) { }
ngOnInit(): void {
this.getSurveys();
this.keys = Object.keys(this.surveys);
}
getSurveys(): void {
this.surveyService.getSurveys().then(surveys => this.surveys = surveys);
}
}
由于我在json对象中获取数据,我尝试使用下面的代码转换为数组,以便我可以在HTML中使用* ngFor进行迭代。
this.keys = Object.keys(this.surveys);
但是当我运行代码时,我收到错误
TypeError: Cannot convert undefined or null to object
有人可以告诉我哪里出错了吗?
答案 0 :(得分:2)
@JB Nizet的评论是正确的解决方案,我在这里给出了明确代码的答案。
export class SurveysComponent implements OnInit {
title = 'Survey List';
surveys: Survey[];
keys: String[];
selectedSurvey: Survey;
constructor(private router: Router,
private surveyService: SurveyServiceService) { }
ngOnInit(): void {
this.getSurveys().then(surveys => {
this.surveys = surveys;
this.keys = Object.keys(this.surveys);
});
}
getSurveys(){
return this.surveyService.getSurveys();
}
}
答案 1 :(得分:0)
我尝试使用烟斗,但我遇到了同样的问题。 相反,我将其用作解决方法。
.subscribe(
res =>
{
this.apiarray = []; <--- Empty array here
console.log("response form api : " + JSON.stringify(res));
this.ResultfromApi= res;
this.apiarray.push(this.PatientInfoFromApi);
}
现在你只是迭代数组而不是对象。在模板中, 你的* ngFor循环就像这样
<tr *ngFor="let item of apiarray">
<td>{{item.specific_key_to_your_result}}</td>
...
</tr>