我正在循环嵌套对象以获取一些数据。这是可行的,但我似乎无法返回数据并在其他地方使用它。
我尝试过将循环放入 promise 中,但也无济于事。我做错了什么?
data: any = {
'1234': {
url: 'https://example1.com/',
path: 'uploads',
link: 'https://example1.com/uploads',
},
'5678': {
url: 'https://example2.com/',
path: 'uploads',
link: 'https://example2.com/uploads',
}
}
onSubmit(formData) {
this.formdata = formData;
Object.keys(this.data).forEach(key => {
if (key == this.formdata.pin) {
const url = this.data[key].url;
// have also tried this.url to no avail
}
});
// says undefined
console.log(url);
// set up headers, etc...
// I need to use here
this.http.post(url, body, head)
...
}
最佳答案
onSubmit(formData) {
this.formdata = formData;
let url; // Define here so that its accessible
Object.keys(this.data).forEach(key => {
if (key === this.formdata.pin) {
url = this.data[key].url;
// have also tried this.url to no avail
}
});
// Now url is in scope
console.log(url);
...
}
关于javascript - 如何从 Angular 中的 foreach 循环返回数组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56350665/