In my Angular app I am pulling in some data via an asynchronous call. Then, once I have that data, I have a function (see below) that iterates over that array and gets a record_id for a passed-in corresponding stageName. I'm running into a ts error however -- there is a red squigly under stageRecords (see asterixes below), and the error is:
[ts] Type 'Observable' is not assignable to type 'any[]'.
Property 'length' is missing in type 'Observable'.
This is my code:
public async getStageIdByName(stageName)
{
let stageRecords = [];
**stageRecords** = await this.getAllStages();
if (stageName && stageRecords) {
console.log('stageRecords: ', stageRecords);
for (let record of stageRecords) {
if (record.stage === stageName) {
let stageId = record._id;
console.log(`stageId for ${stageName} is ${stageId}`);
return stageId;
}
}
}
}
What do I need to change to address this? I tried using Array.from()
but this doesn't resolve the issue of this being an observable, which apparently makes this move impossible. How can I address getting an array from the response to this.getAllStages()
?
UPDATE: After a suggestion I imported the toPromise() operator, and then changed my code to look like this:
public async getStageIdByName(stageName)
{
let stageRecords = [];
stageRecords = await this.getAllStages().toPromise();
if (stageName && stageRecords) {
console.log('stageRecords: ', stageRecords);
for (let record of stageRecords) {
if (record.stage === stageName) {
let stageId = record._id;
console.log(`stageId for ${stageName} is ${stageId}`);
return stageId;
}
}
}
}
This seems like the right track, however, I'm now getting this error:
Type 'Response' is not assignable to type 'any[]'.
Property 'length' is missing in type 'Response'.
By the way, my getAllStages() function looks like this:
public getAllStages()
{
let stageRecords;
let recordsArray;
let fn = response => {
stageRecords = response.data;
if (stageRecords) {
recordsArray = Array.from(stageRecords);
return recordsArray;
}
};
return this.stageService.getStages((fn));
}