Уничтожение API https://randomuser.me/api/ для захвата названия, фамилии и имени, а также большой фотографии профиля пользователя, возвращенного API - PullRequest
2 голосов
/ 10 апреля 2019

Я пытаюсь получить некоторые данные (название, фамилию, имя, а также большую фотографию профиля пользователя, возвращенного API.) Из API https://randomuser.me/api/,, которые, похоже, не работают.

const displayUserPhotoAndName = (data) => {
    if(!data) return;

    // add your code here

    let {results} = data;

    let [profile] = results;

    document.querySelector('h2').textContent = profile.name.title +' '+ profile.name.last +' '+ profile.name.first;

    document.querySelector('img').src = profile.picture.large;


    displayExtraUserInfo(profile);
    clearNotice();
  };

  const getAUserProfile = () => {
    const api = 'https://randomuser.me/api/';

    // make API call here

    fetch(api)
    .then((resp) => resp.json())
    .then(data => {displayUserPhotoAndName()});

    notify(`requesting profile data ...`);
  };



  const displayBirthdate = ({dob = 'dob'}) => {
    document.querySelector('.details').textContent = dob.age;
  }

  const displayPhone = ({phone = 'phone', cell = 'cell'}) => {
    document.querySelector('.details').textContent = phone + ', ' + cell;
  }

  const displayAddress = ({location = 'location'}) => {
    document.querySelector('.details').textContent = location.street + ', ' + location.city + ', ' + location.state;
  }

Ответы [ 2 ]

0 голосов
/ 10 апреля 2019

Вот как вы можете это сделать, а также обрабатывать неверные данные со значениями по умолчанию. Кроме того, не забудьте передать data вашей функции в обратном вызове then:

const display = data => {
  const { results: [{ name: { title, first, last } = {}, picture: { large } = {} }] = [] } = data || {};

  console.log(title, first, last, large);
};

fetch('https://randomuser.me/api/').then(r => display(r.json()));
0 голосов
/ 10 апреля 2019

Вы передаете data функции. Как показано ниже

const getAUserProfile = () => {
    const api = 'https://randomuser.me/api/';

    // make API call here

    fetch(api)
    .then((resp) => resp.json())
    .then(data => {displayUserPhotoAndName(data)});  //this line is changed

    notify(`requesting profile data ...`);
}; 

Вот строка, которая получит все необходимые свойства

let {results:[{ name: { title , first , last } , picture:{ large } }]} = data;
...