我如何 return 来自 Angular 中的 foreach 循环的数组数据

How do I return array data from a foreach loop in Angular

我正在遍历嵌套对象以获取一些数据。这行得通,但我似乎无法 return 数据并将其用于其他地方。

我试过将循环放在一个 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);

    ...
}

将您的 forEach 切换为 map 可以简化此过程; map return 值,而 forEach 没有。

旧:

Object.keys(this.data).forEach(key => {
    if (key == this.formdata.pin) {
        const url = this.data[key].url;
    }
});

// says undefined
console.log(url);

新:(我还根据下面的评论在此处添加了 ===

const urls = Object.keys(this.data).map(key => {
    if (key === this.formdata.pin) {
        return this.data[key].url;
        // have also tried this.url to no avail
    }
});

console.log(urls);

map docs and forEach docs