I have written a service for an API call to fetch the data. Below is my service code.
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);
}
}
Below is my component for getSurveys function
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);
}
}
Since I am getting data in json object I tried to convert into array by using below code, so that I can iterate it using *ngFor in the HTML.
this.keys = Object.keys(this.surveys);
But when I run the code I receive an error as
TypeError: Cannot convert undefined or null to object
Can someone please let me know where I went wrong?