2017-10-13 10 views
0

최선의 방법을 이해하는 데 어려움이 있습니다.가져 오기 호출을 중첩하여 중첩 된 데이터에 액세스하는 방법?

내 목표는 중첩 된 데이터를 표시하는 것입니다. JSON을 포함하는 페이지에 저를 필요 https://horizons-json-cors.s3.amazonaws.com/products.json

을 -

나는이 URL을 가져올 사용합니다. json 안에는 3 개의 URL이 있습니다. 각 URL에는 필요한 데이터가 들어 있습니다.

지금까지는 첫 번째 레이어에 액세스했으며 항목 URL 배열을 보유하고 있습니다. 나는 외부 가져 오기 호출 내부 메신저 동안 데이터를 가져 오는 방법을 이해하지 않는 것 같아요. 여기 내 코드는 지금까지의

(결과는 각 URL이 내가 필요로하는 데이터가 포함 된 URL의 배열입니다.) :

componentDidMount() { 
    console.log('Fetch'); 
    fetch("https://horizons-json-cors.s3.amazonaws.com/products.json") 
    .then((resp) => (resp.json())) 
    .then((json) => { 
     var productUrlArr = []; 
     for (var i = 0; i < json.length; i++) { 
     productUrlArr.push(json[i].url); 
     } 
    .catch((err) => { 
     console.log('error', err); 
    }); 
    }   

하면 너희들이 나를 도와 정말 방법에 액세스하는 방법을 통해 걸을 수 있다면 다음 수준의 데이터, 나는 정말 감사 할 것입니다.

+0

는 아래의 API 호출의 응답을 할 수 있나요? –

+0

소유하고 계신 API입니까? 그렇다면 다른 JSON 파일에 대한 링크 대신 실제로 제품의 데이터를 반환하도록 API를 변경해야한다는 말은 나에게 들립니다. 그렇지 않으면 첫 번째 JSON 파일을 가져온 다음 각 요소를 반복하고 _additional_PEREMENT를 호출해야하므로 매우 비효율적입니다. – dmon

+0

그것은 내가 소유하고있는 API가 아닙니다. 우리 학교에서 중첩 된 데이터로 작업하는 법을 가르쳐주는 연습입니다. 나는 그것이 비효율적 인 것을 깨닫는다. 그러나 나는 그것과 함께 일하는 방법을 배워야한다. 내 문제는 외부 가져 오기 호출 내부에서 각 항목/URL을 반복하고 호출하는 방법을 알아내는 것입니다. – aglaze

답변

0

코드에 약간의 오류가 있습니다.

당신이 배열에서 데이터를 사용할 수 있습니다 그것으로 .catch

전에 })를 실종.

componentDidMount(){ 
    console.log('Fetch'); 
    fetch("https://horizons-json-cors.s3.amazonaws.com/products.json") 
    .then((resp) => (resp.json())) 
    .then((json) => { 
     var productUrlArr = []; 
     for (var i = 0; i < json.length; i++) { 
     productUrlArr.push(json[i].url); 
     } 
     console.log(productUrlArr); 
    }).catch((err) => { 
     console.log('error', err); 
    }); 
} 

희망이 있습니다.

0

간단합니다. 먼저 모든 URL을 먼저 얻으십시오. 그런 다음 매핑하여 Promise.all에 전달합니다.

fetch("https://horizons-json-cors.s3.amazonaws.com/products.json") 
    .then((resp) => (resp.json())) 
    .then((json) => { 
    Promise.all(json.map(product => 
     fetch(product.url).then(resp => resp.text()) 
    )).then(texts => { 
     // catch all the data 
    }) 
    }).catch((err) => { 
    console.log('error', err); 
    }); 
당신은 내부 URL에 너무 이런 식으로 데이터를 가져올 수 있습니다
2

,

// 1. Outer Fetch call initiated here 
fetch("https://horizons-json-cors.s3.amazonaws.com/products.json") 
.then(res => { 
    return res.json() 
}) 
.then(res => { 

    // 2. array for storing url's retrieved from response 
    var urlArray = [] 

    if (res.length > 0) { 

     // 3. Push url inside urlArray 
     res.map(data => urlArray.push(data.url)) 
    } 

    // 4. an array of urls 
    return urlArray 
}) 
.then(urls => { 

    // Return an promise which will return "JSON response" array for all URLs. 
    // Promise.all means “Wait for these things” not “Do these things”. 

    return Promise.all(urls.map(url => { 
     // Take url fetch response, return JSON response 
     return fetch(url).then(res => res.json()) 
    } 
    )) 
}) 
.then(res => { 
    // Store all objects into array for later use 
    var objArr = res; return objArr 
    }) 
//.then(...)