【发布时间】:2019-04-19 16:45:18
【问题描述】:
在我的 Angular 应用程序中,我需要将数据存储到一个数组中,该数组在初始阶段为空。
示例:
someFunction() {
let array = [];
console.log("step 1");
this.service.getRest(url).subscribe(result => {
result.data.forEach(element => {
console.log("step 2");
array.push(element); // Pushing all the objects comes from res.data
});
console.log("step 3");
});
console.log("step 4");
}
这里我列出了console.log() 的步骤顺序。
调用函数时的顺序是,
第 1 步 第 4 步 第2步 第三步
在第 1 步之后,第 4 步调用,然后第 2 步调用。所以如果我 console.log(array) 代替第 4 步,它会再次给出空数组。
但是代替step 2 and 3 它提供了价值。从服务中出来,价值是空的。
因此我总是在array 中得到空值。
即使有一段时间的服务调用和响应返回,请帮助我将数据存储到变量中。
修改代码试了半天还是不行..
编辑:
我在下面给出了我目前正在使用的实时应用程序stackblitz链接https://stackblitz.com/edit/angular-x4a5b6-ng8m4z
在此演示中查看文件https://stackblitz.com/edit/angular-x4a5b6-ng8m4z?file=src%2Fapp%2Fquestion.service.ts
我在哪里使用服务调用.. 如果我输入async getQuestions() {},则会给出questions.forEach of undefined 的错误
在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 = [];
//In the above JSON having empty values in "options": [],
this.jsonData.forEach(element => {
if (element.elementType === 'textbox') {
questions.push(new TextboxQuestion(element));
} else if (element.elementType === 'dropdown') {
//Need to push the data that comes from service result (res.data) to the options
questions.push(new DropdownQuestion(element));
console.log("step 1");
//The service which i call in real time..
// return this.http.get(element.optionsUrl).subscribe(res => {
//res.data has the following array, Using foreach 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) give values as the above [
// { "key": 'average'...
console.log("step 3");
// console.log(element.options) give values as the above [
// { "key": 'average'...
// });
console.log("step 4");
//But here console.log(element.options) gives empty
}
});
return questions.sort((a, b) => a.order - b.order);
}
【问题讨论】:
-
不确定是否理解问题,因为看起来您已经有了解决方案:服务调用是异步的,因此您将在其回调中获得结果(步骤 2 和 3)。在这里你可以成功填写
array,所以你需要对array做什么,在服务回调中发起。 -
我认为这基本上只是旧经典的另一个复制品stackoverflow.com/questions/14220321/…
-
@Zim,但是如果我用 console.log(array) 代替第 4 步,那么它给出空数组,但代替第 2 步和第 3 步,它给出值..
-
@undefined: 是的,因为到了第4步的时候,异步调用还没有结束!
-
将结果放入 setTimeout
标签: javascript angular typescript angular-services angular4-router