I have a function that calls an http.get to an API and it has a return type of promise. I'd like to handle/sort the returned data. Do I need to convert it from a Promise into an array of objects to iterate over it? Here is the function:
getCandidates(): Promise<Candidate[]> {
return this.http.get(url)
.retry(2)
.map(x => {
var result: Candidate[] = x.json();
return result;
})
.toPromise();
}
and I call the function by stating:
this.candidates = this.getCandidates();
So I now have this candidates object of type Promise<Candidate[]> but I'd like to have it be of type Candidate[] so I can work with it, e.g. candidates.length etc. How should I go about this? Maybe I'm thinking of this the wrong way.
Edit: trying to use the code.
ionViewDidLoad() {
//Retrieves candidates and stores into an array
this.getCandidates().then(candidates => this.candidates = candidates);
console.log(this.candidates);
}
The console logs an empty array. I also tried passing it to a sort function but none of the data was present. Which is strange because in the html if I *ngFor over candidates I get the data (which is why I thought it was working properly before).
mapthis.getCandidates().then(function(candidates) { ... });