javascript - 如何从 Angular 中的 foreach 循环返回数组数据

标签 javascript angular ionic-framework ionic3

我正在循环嵌套对象以获取一些数据。这是可行的,但我似乎无法返回数据并在其他地方使用它。

我尝试过将循环放入 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/

相关文章:

javascript - 使用nodejs/express 出现意外的换行符

angular - TypeScript:无法读取 datepipe.transform 中未定义的属性 'transform'

javascript - 在 Stackblitz 上使用 HttpClient 读取 data.json?

javascript - 无法从 TS 文件访问外部 JS 文件的功能

javascript - 如果有空格或非数字字符,HTML5 input type=number value 在 Webkit 中为空?

javascript - 将悬停 SelectInteraction 与 ol.events.condition.mouseMove 结合使用时,OpenLayers 3 中的拖动 map 丢失

javascript - 从回调中触发时,函数不会返回任何值

angular - 根据喜欢/不喜欢动态更改 ionic 图标颜色

css - 当高度超过最大高度时使 ionic 文本区域可滚动

javascript - 连接两个 base64 URL 字符串(图像)