Within my Angular application, I have a requirement to store data in an array that is initially empty.
For example:
someFunction() {
let array = [];
console.log("step 1");
this.service.getRest(url).subscribe(result => {
result.data.forEach(element => {
console.log("step 2");
array.push(element); // Adding all objects from res.data
});
console.log("step 3");
});
console.log("step 4");
}
Here are the console.log()
steps in order:
The sequence when calling the function was,
Step 1 Step 4 Step 2 Step 3
After step 1, step 4 is executed followed by step 2. If I console.log(array)
instead of step 4, it shows an empty array again.
However, instead of step 2 and 3
, it does show values. The issue arises after the service call, resulting in an empty value for the array
.
Thus, I consistently encounter an empty array and require assistance in persisting data even during the service call's time duration.
I've made numerous code modifications but haven't been able to resolve the issue.
Edit:
Below is a link to a real-time application I am working on in stackblitz: https://stackblitz.com/edit/angular-x4a5b6-ng8m4z
In this demo, please refer to the file: https://stackblitz.com/edit/angular-x4a5b6-ng8m4z?file=src%2Fapp%2Fquestion.service.ts
Within the service.ts
jsonData: any = [
{
"elementType": "textbox",
"class": "col-12 col-md-4 col-sm-12",
"key": "project_name",
"label": "Project Name",
"type": "text",
"value": "",
"required": false,
"minlength": 3,
"maxlength": 20,
"order": 1
},
{
"elementType": "textbox",
"class": "col-12 col-md-4 col-sm-12",
"key": "project_desc",
"label": "Project Description",
"type": "text",
"value": "",
"required": true,
"order": 2
},
{
"elementType": "dropdown",
"key": 'project',
"label": 'Project Rating',
"options": [],
"order": 3
}
];
getQuestions() {
let questions: any = [];
// The JSON above contains empty values in "options": [],
this.jsonData.forEach(element => {
if (element.elementType === 'textbox') {
questions.push(new TextboxQuestion(element));
} else if (element.elementType === 'dropdown') {
// Need to populate options with data from the service result (res.data)
questions.push(new DropdownQuestion(element));
console.log("step 1");
// Real-time service call..
// return this.http.get(element.optionsUrl).subscribe(res => {
// "res.data" has the following array, iterating through and pushing to elements.options.
// [
// { "key": 'average', "value": 'Average' },
// { "key": 'good', "value": 'Good' },
// { "key": 'great', "value": 'Great' }
// ],
// res.data.forEach(result => {
console.log("step 2");
// element.options.push(result);
// });
// console.log(element.options) gives values as shown above [
// { "key": 'average'...
console.log("step 3");
// console.log(element.options) gives values as shown above [
// { "key": 'average'...
// });
console.log("step 4");
// However, console.log(element.options) results in empty output
}
});
return questions.sort((a, b) => a.order - b.order);
}