Как получить массив свойств объекта в fetch, а затем передать его во второй вызов fetch? - PullRequest
0 голосов
/ 26 сентября 2019

У меня есть компонент, который зависит от 2-х конечных точек для получения имени нужной программы.У меня есть 2 конечные точки.Первая конечная точка возвращает список программ, который представляет собой массив объектов.В настоящее время он возвращает только 4 программы ( 2 с идентификатором программы "13" и две другие с идентификатором программы "14" ).Вторая конечная точка зависит от этих программных идентификаторов, которые мне как-то нужны, чтобы передать ее второй конечной точке, избежать дубликатов и отделить ее запятой.Например:

Ответ первого вызова:

{
  "programs": [
    { "id": 1, "organization": {"organizationId": 2000}, "programId": 13 },
    { "id": 2, "organization": {"organizationId": 2001 }, "programId": 13 },
    { "id": 22, "organization": {"organizationId": 2002 }, "programId": 14 },
    { "id": 20, "organization": {"organizationId": 2000 }, "programId": 14 }
  ]
}

Второй вызов вызова: api / v1 / program / programlist / 13,14

В коде это то, что я сделал до сих пор:

fetch('/api/v1/organizationrelationship/organizationprograms', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
  }
})
.then(res => res.json())
.then(res => {
  if(res) {
    _.map(res.programs, (program, index) => {
      fetch(`/api/v1/program/programlist/${program.programId}`, { // this is passing all 4 programId individually
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        }
      })
      .then(res => res.json())
      .then(res => {
        if(res) {
          console.log("res: ", res)
        }
      })
    })
  }
})

Желаемый рабочий процесс, который я ищу:

  1. Первый вызов выборки выполнен успешно
  2. затем переходит ко второму вызову извлечения
  3. и передает ID программы в URL
  4. api / v1 / program / programlist / 13,14
  5. а затем я сохраняю ответ в состоянии компонента

1 Ответ

1 голос
/ 26 сентября 2019

Попробуйте следующий фрагмент кода:

fetch('/api/v1/organizationrelationship/organizationprograms', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
  }
})
.then(res => res.json())
.then(res => {
  if(res) {
    // gets all the ids from the response and make them a set to remove duplicate
    let ids = new Set(res.proprams.map( (program, index) => return program.programId));
    // convert the set into and array and the use the toString function to make them comma seperated
    let params = Array.from(ids).toString()
      fetch(`/api/v1/program/programlist/${params}`, { // this is passing all 4 programId individually
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        }
      })
      .then(res => res.json())
      .then(res => {
        if(res) {
          //here you can now save the response to state
          console.log("res: ", res)
        }
      })
  }

})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...